linux中的信号量操作,接收SIGSEGV和分段错误,哪部分错了?
发布时间:2020-12-14 00:35:17 所属栏目:Linux 来源:网络整理
导读:我的线程功能是: #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(se
|
我的线程功能是:
#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 : %dn",semval);
}
}
void *cf(void *arg) /*consumer function*/
{
int semval;
while(running)
{
sleep(1);
sem_wait(&sem);
sem_getvalue(&sem,&semval);
printf("consume : %dn",semval);
}
}
主要功能是: int main()
{
pthread_t pf,cf;
ret = sem_init(&sem,16);
pthread_create(&pf,NULL,(void *)pf,NULL); /*create producer*/
pthread_create(&cf,(void *)cf,NULL); /*create consumer*/
sleep(1);
running = 0;
pthread_join(pf,NULL);
pthread_join(cf,NULL);
sem_destroy(&sem);
return 0;
}
当我运行可执行文件时,它返回分段错误.我认为该程序可能访问无效内存,但我不知道我的代码的哪一部分是错误的! 解决方法
您已使用相同的名称命名了线程变量和函数:pf和cf.所以变量
shadow是函数名.变量和函数具有相同的名称永远不是一个好主意.
更改 pthread_create(&pf,NULL); /*create producer*/ pthread_create(&cf,NULL); /*create consumer*/ 至 pthread_create(&pf,producer,consumer,NULL); /*create consumer*/ 并分别将您的功能重命名为生产者和消费者.请注意,我已删除的转换也是错误的(即使你正确投射也是不必要的). 您将从线程函数返回任何值.线程函数应该返回void *.所以你需要调用 另一个主要问题是您正在访问运行的变量而没有任何同步导致race condition.这是undefined behaviour.根据线程调度,如果主线程设置在线程执行之前运行为0,那么您的线程可能不会执行while循环一点都不 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
