例如 gcc -pthread -o test main.cpp
另外你的线程创建的不对,函数指针不能强转类型(这里也不用转)
pthread_create(&producter_t,NULL,(void*)producter_f,NULL)
pthread_create(&consumer_t,NULL,(void*)consumer_f,NULL)
应该是
pthread_create(&producter_t,NULL,producter_f,NULL)
pthread_create(&consumer_t,NULL,consumer_f,NULL)
帮你修改了一下,编译运行没问题,修改的地方都标出来了,由于不知道你程序的功能,所以没有对你的程序逻辑进行分析
#include <stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
//----------------以下是修改的部分
sem_t in
sem_t out
sem_t handout
sem_t handin
sem_t goout
//----------------
int counter=0
void * studentIn(void *a)
{
sem_wait(&in)//修改
counter++
printf("%d\n",counter)
if(counter==30)
{
sem_post(&handout)//修改
return NULL
}
sem_post(&in)//修改
return NULL
}
void * fteacherhandout(void *b)
{
sem_wait(&handout)//修改
printf("teacher said:hand out over\n")
sem_post(&handin)//修改
return NULL
}
void * studentout(void *c)
{
sem_wait(&handin)//修改
sem_wait(&out)//修改
counter--
printf("%d\n",counter)
if(counter==0)
{
sem_post(&goout)//修改
return NULL
}
sem_post(&out)//修改
}
void * fteacherout(void *d)
{
sem_wait(&goout)//修改
printf("teacher go out")
return NULL
}
void main()
{
int i=0
//----------------以下是修改的部分
sem_init(&in,0,1)
sem_init(&out,0,1)
sem_init(&handin,0,0)
sem_init(&handout,0,0)
sem_init(&goout,0,0)
//----------------
pthread_t thread1[30],thread2[30],teacher1,teacher2
pthread_attr_t attr
pthread_attr_init(&attr)
for(i=0i<30i++)
{
pthread_create(&thread1[i],&attr,studentIn,NULL)
}
for(i=0i<30i++)
{
pthread_create(&thread2[i],&attr,studentout,NULL)
}
pthread_create(&teacher1,&attr,fteacherhandout,NULL)
pthread_create(&teacher2,&attr,fteacherout,NULL)
return
}
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)