讀者寫者問題html
參考連接 http://c.biancheng.net/cpp/html/2601.html併發
讀者優先post
[ligang@localhost ~]$ cat read.c #include<stdio.h> #include<stdlib.h> #include<pthread.h> #include<sys/time.h> #include<semaphore.h> pthread_mutex_t mutex; sem_t rw; int delay = 1; int counter=0; void *writer(void *param) { sem_wait(&rw); printf("it is writting!!!\n"); usleep(2000000); sem_post(&rw); sleep(4); return NULL; } void *reader(void *parm) { pthread_mutex_lock(&mutex); if(counter==0) { sem_wait(&rw); } counter++; printf("add the [%d] reader\n",counter); pthread_mutex_unlock(&mutex); usleep(2000000); printf("it is reading\n"); pthread_mutex_lock(&mutex); printf("delete the [%d] reader\n",counter); counter--; if(counter==0) { sem_post(&rw); } pthread_mutex_unlock(&mutex); return NULL; } int main() { pthread_t tid_w,tid_r; void *retval; pthread_mutex_init(&mutex,NULL); sem_init(&rw,0,1); pthread_create(&tid_w,NULL,writer,NULL); pthread_create(&tid_r,NULL,reader,NULL); pthread_create(&tid_r,NULL,reader,NULL); pthread_create(&tid_w,NULL,writer,NULL); pthread_join(tid_w,&retval); pthread_join(tid_r,&retval); return 0; }
缺點沒法解決二者之間的併發問題.net
運行結果htm
[ligang@localhost ~]$ gcc read.c -lpthread
[ligang@localhost ~]$ ./a.out
it is writting!!!
add the [1] reader
add the [2] reader
it is reading
delete the [2] reader
it is reading
delete the [1] reader
it is writting!!!blog