- #include
- #include
- #include
- #include
- #include
- #include
- #define SIZE 3
- #define STR_SIZE 20
- pthread_mutex_t mutex; //全局變量對main 及 線程函數(shù)都可見
- sem_t read_sem, write_sem; //全局變量對main 及 線程函數(shù)都可見
- struct _buf_
- {
- char* buf[SIZE];
- int front, rear;
- }buffer; //循環(huán)隊(duì)列結(jié)構(gòu)體
- void thread(void)
- {
- while(1)
- {
- if(0 != sem_wait(&read_sem))
- {
- perror("sem_wait_0");
- exit(1);
- }
- if(0 != pthread_mutex_lock(&mutex))
- {
- perror("pthread_mutex_lock_0");
- exit(1);
- }
- fputs("output characters:\n",stdout);
- fputs(buffer.buf[buffer.front],stdout);
- buffer.front = (buffer.front + 1) % SIZE;
- if(0 != pthread_mutex_unlock(&mutex))
- {
- perror("pthread_mutex_lock_0");
- exit(1);
- }
- if(0 != sem_post(&write_sem))
- {
- perror("sem_wait_0");
- exit(1);
- }
- sleep(10);
- }
- }
- int main(void)
- {
- //初始化循環(huán)隊(duì)列結(jié)構(gòu)體
- int i;
- bufferbuffer.front = buffer.rear = 0;
- for(i=0; i < SIZE; i++)
- {
- buffer.buf[i] =(char*) malloc(STR_SIZE);
- }
- //初始化 互斥鎖
- //存在警告 pthread_mutexattr_t mutex_attr = PTHREAD_MUTEX_INITIALIZER;
- if(0 != pthread_mutex_init(&mutex, NULL))
- {
- perror("pthread_mutex_init\n");
- exit(1);
- }
- //初始化信號(hào)量
- if(0 != sem_init(&read_sem, 0, 0))//linux進(jìn)程間的信號(hào)共享還未能實(shí)現(xiàn),參數(shù)PSHARE為0,而且還沒有進(jìn)行寫操作沒有數(shù)據(jù)可讀,將參數(shù)vaule設(shè)置為0,進(jìn)行阻塞
- {
- perror("sem_init_0\n");
- exit(1);
- }
- if(0 != sem_init(&write_sem, 0, 2))
- {
- perror("sem_init_1\n");
- exit(1);
- }
- //創(chuàng)建兩個(gè)子線程
- pthread_t thd0,thd1;
- if(0 != pthread_create(&thd0,NULL,(void*)thread,NULL))
- {
- perror("pthread_create_0\n");
- exit(1);
- }
- if(0 != pthread_create(&thd1,NULL,(void*)thread,NULL))
- {
- perror("pthread_create_1\n");
- exit(1);
- }
- //進(jìn)行寫入字符操作
- while(1)
- {
- //寫信號(hào)量阻塞
- if(0 != sem_wait(&write_sem))
- {
- perror("sem_wait_1");
- exit(1);
- }
- //上互斥鎖所進(jìn)行寫入操作
- if(0 != pthread_mutex_lock(&mutex))
- {
- perror("pthread_mutex_lock_1");
- exit(1);
- }
- fputs("pls enter 20 character:\n",stdout);
- //讀標(biāo)準(zhǔn)輸入文件
- if(NULL == fgets(buffer.buf[buffer.rear],STR_SIZE,stdin))
- {
- perror("fgets\n");
- exit(1);
- }
- if(0 == strncmp("end\n",buffer.buf[buffer.rear],3))
- {
- printf("manual exit successfully\n");
- exit(1);
- }
- buffer.rear = (buffer.rear+1)% SIZE;
- //解互斥鎖
- if(0 != pthread_mutex_unlock(&mutex))
- {
- perror("pthread_mutex_lock_1");
- exit(1);
- }
- if(0 != sem_post(&read_sem))
- {
- perror("sem_wait_1");
- exit(1);
- }
- sleep(1);
- }
- return 0;
- }
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)公司!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了儀隴免費(fèi)建站歡迎大家使用!