成员函数访问多线程程序?

quwei197874 2011-12-27 01:41:56
class test
{
public:
test(){}
~test(){}
void create_thread();
static void *thread_function(void*)
{
test *pTest= (test *)pParam;
pTest->fun();
}

};

void test::create_thread()
{
pthread_t thread;
pthread_create(&thread, NULL, test::thread_function, this);

}

int main()
{
test testobj;
return 0;
}

上面代码为什么进入不到thread_function()这个函数中?应该如何修改??
...全文
109 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
薛定谔之死猫 2011-12-27
  • 打赏
  • 举报
回复

#include <iostream>
#include <pthread.h>

using namespace std;

class Test
{
public:
Test(){}
~Test(){}
void func(){cout<<"Fuck it again!"<<endl;}
static void *thread_func(void *param){
Test *p = (Test *)param;
p->func();
}

void create_thread(){
pthread_t thread;
int res = pthread_create(&thread,NULL,thread_func,this);
cout<<res<<endl;
}

};

int main(int argc,char *argv[]){
Test test;
test.create_thread();
return 0;
}

薛定谔之死猫 2011-12-27
  • 打赏
  • 举报
回复
在这里把用于测试的两个小程序贴出来吧

#include <iostream>
#include <pthread.h>

using namespace std;

void *thread_func(void *param);

class Test
{
public:
Test(){}
~Test(){}
void func(){cout<<"Fuck it again!"<<endl;}
void create_thread(){
pthread_t thread;
int res = pthread_create(&thread,NULL,thread_func,this);
cout<<res<<endl;
}

};

void *thread_func(void *param){
Test *p = (Test *)param;
p->func();
}


int main(int argc,char *argv[]){
Test test;
test.create_thread();
return 0;
}

薛定谔之死猫 2011-12-27
  • 打赏
  • 举报
回复
通过汇编的分析,两者实现基本是一模一样的,你之所以观察不到是因为主线程过快结束了,在main的return之前追加sleep就能看到很好的效果~

C++的类成员函数编译结果较外部函数编译结果汇编代码较多,主要表现在会插入大量的nop,估计为了玩对齐,所以外部函数作为线程函数的情况线程启动很快,看见执行效果的几率增多
quwei197874 2011-12-27
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 wallwind 的回复:]
int main()
{
test testobj;
return 0;
}


大哥 你没调用void test::create_thread() ~~~
[/Quote]调了,在二楼说了
wintree 2011-12-27
  • 打赏
  • 举报
回复
int main()
{
test testobj;
return 0;
}


大哥 你没调用void test::create_thread() ~~~
quwei197874 2011-12-27
  • 打赏
  • 举报
回复
哪个参数传类指针?
ouyh12345 2011-12-27
  • 打赏
  • 举报
回复
在参数里传类的指针
quwei197874 2011-12-27
  • 打赏
  • 举报
回复
上面代码main函数中少加了testobj.create_thread();

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧