[Linux C程式設計]執行緒之間的同步與互斥
阿新 • • 發佈:2018-12-31
執行緒之間的同步與互斥
我們主要通過生產者與消費者之間的問題來體現執行緒之間的同步與互斥:
具體問題如下:
用執行緒實現:生產者與消費者:
一個緩衝區,兩個執行緒:生產者和消費者,一個放入快取一個從快取取資料,生產者在滿時等待,消費者在空時等待,互斥執行。
原始碼如下:
一個緩衝區,兩個執行緒:生產者和消費者,一個放入快取一個從快取取資料,生產者在滿時等待,消費者在空時等待,互斥執行。
原始碼如下:
<span style="font-family:FangSong_GB2312;font-size:18px;"><strong>#include <stdio.h> #include <pthread.h> #include <semaphore.h> #include <string.h> #include <stdlib.h> #define BUF_SIZE 2048 #define MAX_SIZE 100 sem_t sem_cus; sem_t sem_pro; struct produce_addr //緩衝存放 { int num; char buffer[BUF_SIZE]; }; struct produce_addr p; void customer() //消費者 { char str[MAX_SIZE]; while(1) { sem_wait(&sem_cus); printf("please input message:\n"); scanf("%s",str); strcpy(p.buffer,str); if(strncmp(p.buffer,"quit",4) == 0) //輸入quit退出 { exit(0); } sem_post(&sem_pro); } sleep(1); } void producer() //生產者 { while(1) { sem_wait(&sem_pro); printf("message is %s\n",p.buffer); sem_post(&sem_cus); sleep(1); } } int main() { pthread_t id1; pthread_t id2; sem_init(&sem_pro,0,0); sem_init(&sem_cus,0,1); pthread_create(&id1,NULL,(void *)producer,NULL); pthread_create(&id2,NULL,(void *)customer,NULL); pthread_join(id1,NULL); pthread_join(id2,NULL); sem_destroy(&sem_pro); sem_destroy(&sem_cus); return 0; }</strong></span>