pthread semaphore用法

本篇主要讲解pthread_mutex_t 和pthread_cond_t之间配合的工作以及需要注意的事项:

以下code是在codeblocks中编写~

#include #include #include using namespace std; pthread_mutex_t mutex; pthread_cond_t condition; void *workThread(void *arg) { pthread_mutex_lock(&mutex); pthread_cond_wait(&condition,&mutex); //pthread_detach(pthread_self()); //int *a = (int *)malloc(sizeof(int)); printf("working thread executing ~~~/n"); pthread_mutex_unlock(&mutex); } int main() { pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); mutex = PTHREAD_MUTEX_INITIALIZER; condition = PTHREAD_COND_INITIALIZER; int threadId = 5; pthread_create(&thread,&attr,workThread,(void *)&threadId); //sleep 10ms to let workthread gain mutex lock first~. _sleep(1); pthread_mutex_lock(&mutex); int index = 0; while(index < 10) { printf("main thread executing ~~~/n"); pthread_mutex_unlock(&mutex); index++; } pthread_cond_signal(&condition); _sleep(10); system("pause"); return 0; }  

 

首先pthread_create(&thread,&attr,workThread,(void *)&threadId);创建线程,然后通过_sleep(1);目的是让workThread函数先锁定mutex,这样就不会出现pthread_cond_wait, pthread_cond_signal先后的顺序逻辑错误了。

流程:

mainthread->sleep 1->workThread lock mutex -> pthread_cond_wait unlock mutex -> main thread lock mutex 

-> 然后执行循环里面的事情,虽然中途已经解了锁,但是由于主线程仍然未调用pthread_cond_signal所以直到调用后,workThread

才会执行printf,当然pthread_cond_signal也可以紧紧的跟在pthread_mutex_lock后面,那样一旦在循环中调用了pthread_mutex_unlock后主线程和工作线程将会交叉执行 。这么看来当signal给一个线程时,不会妨碍主线程的执行过程 。

 

下面讲解一下pthread与semaphore的用法:

#include #include #include #include using namespace std; sem_t sem; void *readData(void *arg) { FILE *stream; char data[100]; memset(data,0,100); while(true) { sem_wait(&sem); stream = fopen("data.txt","rb"); fscanf(stream,"%s",data); printf("%s/n",data); fclose(stream); } } void *writeData(void *arg) { FILE *stream ; char *data = "testing"; while(true) { _sleep(5000); stream = fopen("data.txt","wb"); fprintf(stream,"%s",data); fclose(stream); sem_post(&sem); } } int main() { pthread_t thread[2]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); sem_init(&sem,0,0); pthread_create(&thread[0],&attr,readData,NULL); pthread_create(&thread[1],&attr,writeData,NULL); _sleep(10000); system("pause"); return 0; }  

首先注意sem_init中第二个和三个参数的意义:第二个如果不为0代表进程间共享sem,第三个代表sem值的初始值。

这是个读写问题,代表每次必须先写后读,主线程要给子线程足够的时间,_sleep(10000)最多只能写读两轮 。。。

 

你可能感兴趣的:(C/C++)