線程間的互斥量和條件變量

互斥鎖:

PS:互斥鎖的生存週期必須大於用到互斥鎖的線程的生存週期!

靜態分配互斥量:

pthread_mutex_t  mutex=PTHREAD_MUTEX_INITIALIZER;

動態分配互斥量:

pthread_mutex_init(&mutex,NULL);

pthread_mutex_destroy(&mutex);

mutex————互斥鎖。

加鎖:

int pthread_mutex_lock(pthread_t* mutex);

嘗試加鎖:

int pthread_mutex_trylock(pthread_t* mutex);

解鎖:

int pthread_mutex_unlock(pthread_t* mutex);


條件變量:

概念:

線程掛起直到共享數據的某些條件得到滿足。

運行方式:

當線程運行到等待函數時,解開第二個參數的互斥鎖,並等待信號;當接收到第一個參數的信號後,開始搶鎖,搶到鎖後繼續向下執行。

當線程運行到激活函數時,發出一個信號,並繼續執行下面的函數。

等待函數和激活函數必須同時運行纔可以接收到信號。

靜態分配條件變量:

pthread_cond_t  cond=PTHREAD_COND_INITIALIZER;

動態分配條件變量:

pthread_cond_init(&cond,NULL);

pthread_cond_destroy(&cond);

條件等待:

int  pthread_cond_wait(pthread_cond_t*  cond,pthread_mutex_t* mutex);

cond——條件變量。

mutex——互斥鎖。

計時等待:

int  pthread_cond_timedwait(pthread_cond_t* cond,pthread_mutex_t* mutex,const struct timespec* adstime);

abstime——等待時間。

返回值——ETIMEDOUT(超時結束等待)。

單個激活:

int pthread_cond_signal(pthread_cond_t* cond);

返回值——0成功;正數爲錯誤碼。

全部激活:

int pthread_cond_broadcast(pthread_cond_t*  cond);

返回值——0爲成功;正數爲錯誤碼。

代碼:

#include <stdio.h>
#include <pthread.h>
#include <sched.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;

int currency;

void* checkout(void* arg){
	sleep(1);
	for(;;){
		pthread_mutex_lock(&mutex);
		printf("checkout enter\n");
		currency = rand()%2000;		
		printf("spend %d\n",currency);
		if(currency >= 1000){
			printf("signal boss\n");
			pthread_cond_signal(&cond1);
			printf("wait answer\n");
		}
		printf("checkout leave\n");
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
}

void* boss(void* arg){
	for(;;){
		pthread_mutex_lock(&mutex);
		printf("boss enter\n");
		printf("boss wait\n");
		pthread_cond_wait(&cond1,&mutex);
		printf("boss agress\n");
		printf("boss leave\n");
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
}

int main(){
	typedef void*(*func_t)(void*);
	func_t funcs[2] = {boss,checkout};
	pthread_t tids[2];
	int i;
	pthread_setconcurrency(2);
	for(i=0;i<2;i++){
		pthread_create(&tids[i],NULL,funcs[i],NULL);
	}
	for(i=0;i<2;i++){
		pthread_join(tids[i],NULL);
	}	
}


發佈了93 篇原創文章 · 獲贊 44 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章