- #include<pthread.h>
- #include<semaphore.h>
- #include<stdlib.h>
- #include<stdio.h>
- #include<string.h>
- #include<unistd.h>
- #define SIZE 3
- #define STR_SIZE 20
- pthread_mutex_t mutex; //全局变量对main 及 线程函数都可见
- sem_t read_sem, write_sem; //全局变量对main 及 线程函数都可见
- struct _buf_
- {
- char* buf[SIZE];
- int front, rear;
- }buffer; //循环队列结构体
- 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)
- {
- //初始化循环队列结构体
- 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);
- }
- //初始化信号量
- if(0 != sem_init(&read_sem, 0, 0))//linux进程间的信号共享还未能实现,参数PSHARE为0,而且还没有进行写操作没有数据可读,将参数vaule设置为0,进行阻塞
- {
- perror("sem_init_0\n");
- exit(1);
- }
- if(0 != sem_init(&write_sem, 0, 2))
- {
- perror("sem_init_1\n");
- exit(1);
- }
- //创建两个子线程
- 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);
- }
- //进行写入字符操作
- while(1)
- {
- //写信号量阻塞
- if(0 != sem_wait(&write_sem))
- {
- perror("sem_wait_1");
- exit(1);
- }
- //上互斥锁所进行写入操作
- if(0 != pthread_mutex_lock(&mutex))
- {
- perror("pthread_mutex_lock_1");
- exit(1);
- }
- fputs("pls enter 20 character:\n",stdout);
- //读标准输入文件
- 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;
- }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。