Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux培训 > » 正文

linux下用c++产生线程

来源: JoyForce 分享至:

在c++编译环境下编译pthread_create会报错,出现问题的主要原因就是pthread_create的第3个参数——void*(void*)这个回调函数。
下面给出解决方法:

将要调用的函数改成静态函数或全局函数:

#include <iostream> using namespace std; #include <pthread.h>
void *Bar(void *arg) { cout << __PRETTY_FUNCTION__ << endl; } class Foo { public: Foo(); ~Foo(); static void * Bar(void *arg); private: pthread_t tid_self; pthread_t tid_other; }; Foo::Foo() { pthread_create(&tid_self, NULL, &Bar, NULL); pthread_join(tid_self, NULL); pthread_create(&tid_other, NULL, &::Bar, NULL); } Foo::~Foo() { pthread_join(tid_other, NULL); } void * Foo::Bar(void *arg) { cout << __PRETTY_FUNCTION__ << endl; } int main(int argc, char *argv[]) { Foo foo; return 0; }

若要调用类的成员,则用如下方法:

将传递的参数定义为struct:

struct myarg{ //其他参数 Foo* pFoo; }

然后在函数调用中:

void*Foo::Bar(void*arg) { struct myarg* parg = (struct myarg*) arg; Foo* pFoo = parg->pFoo; //下面就可以调用Foo的成员变量了 }


Tags:
分享至:
最新图文资讯
1 2 3 4 5 6
验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史