linux中的信号量 *** 作,接收SIGSEGV和分段错误,哪部分错了?

linux中的信号量 *** 作,接收SIGSEGV和分段错误,哪部分错了?,第1张

概述我的线程功能是: #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; 我的线程功能是:

#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,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 *.所以你需要调用pthread_exit(NULL);或返回一个空指针.

另一个主要问题是您正在访问运行的变量而没有任何同步导致race condition.这是undefined behaviour.根据线程调度,如果主线程设置在线程执行之前运行为0,那么您的线程可能不会执行while循环一点都不

总结

以上是内存溢出为你收集整理的linux中的信号量 *** 作,接收SIGSEGV和分段错误,哪部分错了?全部内容,希望文章能够帮你解决linux中的信号量 *** 作,接收SIGSEGV和分段错误,哪部分错了?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/1023888.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存