1. 程式人生 > >執行緒、互斥鎖與條件變數例項理解

執行緒、互斥鎖與條件變數例項理解

互斥鎖:

初始化程序鎖:

int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);

其中 mutex 為鎖號
attr為屬性

摧毀互斥鎖:

 int pthread_mutex_destroy(pthread_mutex_t *mutex);

加鎖與解鎖:

int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex
); int pthread_mutex_unlock(pthread_mutex_t *mutex);

其中trylock為嘗試加鎖,但不阻塞。

執行緒條件變數:

初始化與摧毀:

int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_init(pthread_cond_t *restrict cond,const pthread_condattr_t *restrict attr);

其中cond為條件變數
attr為屬性。

建立分離執行緒:

int pthread_attr_init(pthread_attr_t *attr); //初始化屬性
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);//設定分離屬性的值

其中detachstate的值:

PTHREAD_CREATE_DETACHED  --->分離
PTHREAD_CREATE_JOINABLE   --->非分離

例項:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<string.h> #define WORK_SIZE 1024 void * thread_function(void *arg);//定義執行緒函式 pthread_mutex_t work_mutex;//定義鎖 char work_area[WORK_SIZE]; pthread_cond_t cid;//定義條件變數 int main(int argc,char *argv[]) { int res; pthread_t a_thread;//建立執行緒id void *thread_result; res = pthread_mutex_init(&work_mutex,NULL);//初始化鎖 if(res !=0) { printf("mutex initialization failed\n"); exit(-1); } if(pthread_cond_init(&cid,NULL)<0)//初始化條件變數 { perror("get cond fail"); exit(-1); } res = pthread_create(&a_thread,NULL,thread_function,NULL);//建立執行緒 if(res !=0) { printf("thread create failed\n"); exit(-1); } if(pthread_mutex_lock(&work_mutex)<0)//鎖住互斥鎖 { perror("father lock cond fail"); exit(-1); } while(1) { printf("input some text,enter 'end' to finish\n"); gets(work_area);//獲取字串 pthread_mutex_unlock(&work_mutex);//解鎖 if(pthread_cond_signal(&cid)<0)//傳送訊號給子執行緒 { perror("signal cond fail"); exit(-1); } if(strcmp(work_area,"end")==0) { break; } if(pthread_cond_wait(&cid,&work_mutex)<0)//等待子執行緒訊號,當收到訊號時,會自動上鎖 { perror("wait cond fail"); exit(-1); } } pthread_mutex_unlock(&work_mutex); printf("waiting for thread to finish...\n"); res = pthread_join(a_thread,&thread_result); if(res !=0) { printf("thread join failed\n"); exit(-1); } printf("thread join \n"); pthread_mutex_destroy(&work_mutex); exit(-1); } void *thread_function(void *arg) { while(strncmp("end",work_area,3)!=0)//如果收到end則跳出 { work_area[0]='\0';//清空 if(pthread_cond_wait(&cid,&work_mutex)<0)//等待父執行緒訊號 { perror("wait cond fail"); exit(-1); } printf("you input %d charactes\n",strlen(work_area)-1); printf("the characters is \"%s\"\n",work_area); pthread_mutex_unlock(&work_mutex);//輸出完後解鎖 if(pthread_cond_signal(&cid)<0)//傳送訊號給父執行緒 { perror("signal cond fail"); exit(-1); } } pthread_mutex_unlock(&work_mutex);//解鎖 pthread_exit(0); }