实验七——线程同步和多线程编程.docxVIP

  • 2
  • 0
  • 约5.31千字
  • 约 8页
  • 2017-10-31 发布于湖北
  • 举报
实验七——线程同步和多线程编程

实验七 线程同步与多线程编程 实验目的: 了解系统中线程同步的基本原理。 了解和熟悉多线程编程和线程访问控制。 实验内容及步骤: 生产者和消费者问题: 截图和分析源程序: 程序代码注释: #include stdio.h #include stdlib.h #include unistd.h #include pthread.h #include errno.h #include sys/ipc.h #include semaphore.h #include fcntl.h #include time.h #include string.h #define FIFO myfifo #define N 5 int lock_var; time_t end_time; char buf_r[100];//定义buf_r数组表示缓冲区 sem_t mutex,full,empty;//互斥信号量mutex,信号量empty表示缓冲池中空缓冲区数量,full表示满缓冲区数量 int fd; void producer(void *arg); void consumer(void *arg); int main(int argc,char *argv[]) { pthread_t id1,id2; pthread_t mon_th_id; int ret; end_time=time(NULL)+10; /*create a named pipe*/ //创建管道 if((mkfifo(FIFO,0777|O_CREAT)0)(errno!=EEXIST)) printf(cannot creat fifoserver\n); printf(Preparing for reading bytes\n); memset(buf_r,0,sizeof(buf_r)); /*open the pipe*/ //打开管道 fd=open(FIFO,O_RDWR|O_NONBLOCK,0); if(fd==-1) { perror(open); exit(1); } /*initialize the mutex to 1*/ //初始化互斥信号量和empty,full缓冲区 ret=sem_init(mutex,0,1); ret=sem_init(empty,0,N); ret=sem_init(full,0,0); if(ret!=0) { perror(sem_init); } ret=pthread_create(id1,NULL,(void*)producer,NULL);//创建producer线程,创建成功返回0 if(ret!=0) perror(pthread create1); ret=pthread_create(id2,NULL,(void*)producer,NULL);//创建consumer线程,创建成功返回0 if(ret!=0) perror(pthread create2); pthread_join(id1,NULL);//等待producer线程结束 pthread_join(id2,NULL);//等待consumer线程结束 exit(0); } void producer(void *arg) { int i,nwrite; while(time(NULL)end_time) { sem_wait(empty);//空缓冲区的信号量值减1 sem_wait(mutex);//互斥信号量值减1变为0,对资源锁定 if((nwrite=write(fd,hello,5))==-1) {if(errno==EAGAIN)

文档评论(0)

1亿VIP精品文档

相关文档