linux中的信号量操作,接收SIGSEGV和分段错误,哪部分错了?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了linux中的信号量操作,接收SIGSEGV和分段错误,哪部分错了?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1614字,纯文字阅读大概需要3分钟。
内容图文
![linux中的信号量操作,接收SIGSEGV和分段错误,哪部分错了?](/upload/InfoBanner/zyjiaocheng/969/cac43bffe99d4c24af8c20d59806227d.jpg)
我的线程功能是:
#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;
}
当我运行可执行文件时,它返回分段错误.我认为该程序可能访问无效内存,但我不知道我的代码的哪一部分是错误的!
解决方法:
您已使用相同的名称命名了线程变量和函数:pf和cf.所以变量shadow是函数名.变量和函数具有相同的名称永远不是一个好主意.
更改
pthread_create(&pf,NULL,(void *)pf,NULL); /*create producer*/
pthread_create(&cf,NULL,(void *)cf,NULL); /*create consumer*/
至
pthread_create(&pf,NULL,producer,NULL); /*create producer*/
pthread_create(&cf,NULL,consumer,NULL); /*create consumer*/
并分别将您的功能重命名为生产者和消费者.请注意,我已删除的转换也是错误的(即使你正确投射也是不必要的).
您将从线程函数返回任何值.线程函数应该返回void *.所以你需要调用pthread_exit(NULL);或返回一个空指针.
另一个主要问题是您正在访问运行的变量而没有任何同步导致race condition.这是undefined behaviour.根据线程调度,如果主线程设置在线程执行之前运行为0,那么您的线程可能不会执行while循环一点都不
内容总结
以上是互联网集市为您收集整理的linux中的信号量操作,接收SIGSEGV和分段错误,哪部分错了?全部内容,希望文章能够帮你解决linux中的信号量操作,接收SIGSEGV和分段错误,哪部分错了?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。