c语言pthread创建线程失败,c++创建线程的常见问题:error: invalid conversion from 'void*' to 'void* (*)(void*)'...

重点:注意,这里只能写gcc,究其原因就是C语言编译器允许隐含性的将一个通用指针转换为任意类型的指针,而C++不允许的。

本人近期在做按tcp流发送数据包的学习,一来二去接触到了多线程。我百度照此写了个多线程代码,如下:

#include

#include

#include

void thread(void *arg);

void thread(void *arg)

{

int i;

for(i = 0; i < 3; ++i){

printf("This is a pthead.\n");

}

}

int main(int argc, char* argv[])

{

pthread_t id;

int i, ret;

ret = pthread_create(&id, NULL, (void*)&thread, NULL);

if(ret){

printf("create thread error: ");

exit(1);

}

for(i = 0; i < 3; ++i){

printf("This is main proccess");

}

pthread_join(id, NULL);

return 0;

}

但是,他爹,我用g++ main.cpp -o -lpthread debug进行编译的时候,这个家伙:error: invalid conversion from 'void*' to 'void* (*)(void*)'不厌其烦地出现在了我的xshell中,弄得我是苦不堪言。

于是,我查看了Posix中建立线程函数的定义:extern int pthread_create (pthread_t *__restrict __threadp,  __const pthread_attr_t *__restrict __attr, void(*__start_routine) (void *), void *__restrict __arg) __THROW;

这个pthread_create()中的第三个参数是载入一个函数,这个函数有一个参数可以传入,返回一个 通用指针。

因此,出现上述错误的解决方法:

1)线程函数定义为void  thread(void* arg),而调用处写为:int ret = pthread_create(&id, NULL, (viod*)&thread, NULL);

2)线程函数定义为void * thread(void* arg),调用处为:int ret = pthead_create(&id, NULL, thread, NULL)。

然后进行编译: gcc main.c -o -lpthread debug,搞定!

注意,这里只能写gcc,究其原因就是C语言编译器允许隐含性的将一个通用指针转换为任意类型的指针,而C++不允许的。

————————————————

原文链接:https://blog.csdn.net/Alpelious/article/details/53486547

*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值