运行下面代码给出结果 #define _GNU_SOURCE #include "sched.h" #include<sys/太阳pes.h> #include<sys/syscall.h> #include<unistd.h> #include <pthread.h> #include "stdio.h" #include "stdlib.h" #include "semaphore.h" #include "sys/wait.h" #include "string.h" int producer(void * args); int consumer(void * args); pthread_mutex_t mutex; sem_t product; sem_t warehouse; char buffer[8][4]; int bp=0; int main(int argc,char** argv){ pthread_mutex_init(&mutex,NULL);//初始化 sem_init(&product,0,0); sem_init(&warehouse,0,8); int clone_flag,arg,retval; char *stack; //clone_flag=CLONE_SIGHAND|CLONE_VFORK //clone_flag=CLONE_VM|CLONE_FILES|CLONE_FS|CLONE_SIGHAND; clone_flag=CLONE_VM|CLONE_SIGHAND|CLONE_FS| CLONE_FILES; //printf("clone_flag=%d\n",clone_flag); int i; for(i=0;i<2;i++){ //创建四个线程 arg = i; //printf("arg=%d\n",*(arg)); stack =(char*)malloc(4096); retval=clone(producer,&(stack[4095]),clone_flag,(void*)&arg); //printf("retval=%d\n",retval); stack=(char*)malloc(4096); retval=clone(consumer,&(stack[4095]),clone_flag,(void*)&arg); //printf("retval=%d\n\n",retval); usleep(1); } exit(1); } int producer(void *args){ int id = *((int*)args); int i; for(i=0;i<10;i++){ sem_wait(&warehouse); pthread_mutex_lock(&mutex); if(id==0) strcpy(buffer[bp],"aaa/0"); else strcpy(buffer[bp],"bbb/0"); bp++; printf("producer %d produce %s in %d\n",id,buffer[bp-1],bp-1); pthread_mutex_unlock(&mutex); sem_post(&product); } printf("producer %d is over!\n",id); exit(id); } int consumer(void *args){ int id = *((int*)args); int i; for(i=0;i<10;i++) { sleep(10-i); //表现线程速度差别 sem_wait(&product); pthread_mutex_lock(&mutex); bp--; printf("consumer %d get %s in %d\n",id,buffer[bp],bp+1); strcpy(buffer[bp],"zzz\0"); pthread_mutex_unlock(&mutex); sem_post(&warehouse); } printf("consumer %d is over!\n",id); exit(id); }
时间: 2024-03-04 21:50:53 浏览: 78
这段代码是一个生产者-消费者模型的实现,使用了线程和信号量。其中,生产者线程通过向 buffer 数组中添加数据来模拟生产商品,消费者线程通过从 buffer 数组中取出数据来模拟消费商品。生产者和消费者线程之间通过信号量进行同步,保证生产者不会在 buffer 数组已满时继续添加数据,消费者不会在 buffer 数组为空时继续取出数据。同时,使用了互斥锁保证线程之间的互斥访问。在程序运行过程中,会创建两个生产者线程和两个消费者线程。每个生产者线程会生产 10 个商品,每个消费者线程会消费 10 个商品。最终程序会输出每个线程生产或消费的商品编号以及 buffer 数组中的状态。
阅读全文