Linux開發——多線程管理

目錄

線程

創建線程

線程退出

線程的私有數據

線程互斥:

條件變量

簡單列子

讀寫鎖

線程信號

線程屬性


線程

獲取線程tpid:syscall(SYS_gettid)   系統調用

創建線程

線程退出

線程的私有數據

線程互斥:

條件變量

簡單列子

#include "stdio.h"
#include "stdlib.h"
#include "pthread.h"
#include "time.h"
#include <unistd.h>


#define BUFFER_SIZE 4
#define OVER (-1)

struct prodcons
{
	int buffer[BUFFER_SIZE];
	pthread_mutex_t lock;
	int readpos,writepos;
	pthread_cond_t notempty;
	pthread_cond_t notfull;
};

struct prodcons buffer;

void init(struct prodcons * prod)
{
	pthread_mutex_init(&prod->lock,NULL);
	pthread_cond_init(&prod->notempty,NULL);
	pthread_cond_init(&prod->notfull,NULL);
	prod->readpos = 0;
	prod->writepos = 0;
}
void put(struct prodcons * prod,int data)
{
	pthread_mutex_lock(&prod->lock);
	while((prod->writepos+1)%BUFFER_SIZE==prod->readpos)
	{
		printf("producer wait for not full\n");
		pthread_cond_wait(&prod->notfull,&prod->lock);
	}
	prod->buffer[prod->writepos] = data;
	prod->writepos++;
	if(prod->writepos >= BUFFER_SIZE)
		prod->writepos = 0;
	pthread_cond_signal(&prod->notempty);
	pthread_mutex_unlock(&prod->lock);
}
void * producer(void *data)
{
	int n;
	for (int i = 0; i < 5; ++i)
	{
		printf("producer sleep 1 second\n");
		sleep(1);
		printf("put thd %d product\n",i);
		put(&buffer,i);
	}
	for (int i = 5; i < 10; ++i)
	{
		printf("producer sleep 3 second\n");
		sleep(3);
		printf("put thd %d product\n",i);
		put(&buffer,i);
	}
	put(&buffer,OVER);
	printf("producer stop!\n");
	return NULL;
}
int get(struct prodcons * prod)
{
	pthread_mutex_lock(&prod->lock);
	while((prod->readpos)%BUFFER_SIZE == (prod->writepos)){
		printf("consumer wait producer!!!%d---%d\n",prod->readpos,prod->writepos);
		pthread_cond_wait(&prod->notempty,&prod->lock);
	}
	int value = prod->buffer[prod->readpos];
	prod->readpos++;
	if(prod->readpos >= BUFFER_SIZE)
	{
		prod->readpos = 0;
	}
	pthread_cond_signal(&prod->notfull);
	pthread_mutex_unlock(&prod->lock);
	return value;
}
void *consumer(void * data)
{
	int a;
	while(1){
		sleep(1);
		a = get(&buffer);
		if(a==-1){
			break;
		}
	}
	return NULL;
}

int main(int argc, char const *argv[])
{
	pthread_t th_a,th_b;
	void * retval;
	init(&buffer);
	pthread_create(&th_a,NULL,producer,0);
	pthread_create(&th_b,NULL,consumer,0);

	pthread_join(th_a,&retval);
	pthread_join(th_b,&retval);
	return 0;
}

讀寫鎖

線程信號

綁定是共享的,屏蔽是分開的

線程屬性

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章