【发布时间】:2015-07-28 06:52:59
【问题描述】:
我的线程函数是:
#include"stdio.h"
#include"sys/types.h"
#include"pthread.h"
#include"semaphore.h"
sem_t sem;
int running = 1;
int ret;
void *pf(void *arg) //producer function
{
int semval;
while(running)
{
sleep(1);
sem_post(&sem);
sem_getvalue(&sem,&semval);
printf("produce : %d\n",semval);
}
}
void *cf(void *arg) /*consumer function*/
{
int semval;
while(running)
{
sleep(1);
sem_wait(&sem);
sem_getvalue(&sem,&semval);
printf("consume : %d\n",semval);
}
}
主要功能是:
int main()
{
pthread_t pf, cf;
ret = sem_init(&sem,0,16);
pthread_create(&pf,NULL,(void *)pf,NULL); /*create producer*/
pthread_create(&cf,NULL,(void *)cf,NULL); /*create consumer*/
sleep(1);
running = 0;
pthread_join(pf,NULL);
pthread_join(cf,NULL);
sem_destroy(&sem);
return 0;
}
当我运行可执行文件时,它返回分段错误。我认为程序可能访问了无效内存,但我不知道我的代码的哪一部分是错误的!
【问题讨论】: