多线程封装

每个成员函数(除了在第 12.6 节介绍的 static 成员函数外)都有一个额外的、隐含的形参 this。
为了理解成员函数的调用,可考虑下面的语句:
total.same_isbn(trans);
就如编译器这样重写这个函数调用,this指针被传入成员函数:
Sales_item::same_isbn(&total, trans);
所以在进行多线程编程的时候遇到了一个编译问题:argument of type ‘void* (test::)(void*)’ does not match ‘void* (*)(void*)’
后来发现将线程处理函数声明为static类型,问题得解。
其实这个原因很简单,当把线程函数封装在类中,this指针会作为默认的参数被传进函数中,从而和线程函数参数(void*)不能匹配,不能通过编译。
另一种理解
类的静态函数不属于该类的任何一个对象,而是属于类本身,所以不受对象局部变量的影响,在运行时可以直接调用类的静态函数,从而启动线程!

相反,如果一个类的一个局部对象的生命周期结束了,难道线程函数就不能用了吗?


#include<iostream>
#include <pthread.h>
using namespace std;

class test
{
	public:
		int testnum;
		test();
		~test();
		void doPthread();
		static void * createPthread(void *ptr);	
};

test::test()
{	
	testnum=1;
}
test::~test()
{
}
void test::doPthread()
{
	cout << "create_thread" << endl;
	pthread_t pthread;
	pthread_create(&pthread, NULL, createPthread, (void*)this );
	cout << "pthread_join" << endl;
	pthread_join(pthread, NULL);
	cout << "end" << endl;
}
void *test::createPthread(void *ptr)
{
	test* tp = (test *)ptr;
	while(1)
		cout << tp->testnum << endl;
}

int main()
{
	test t;
	t.doPthread();
	return 0;	
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值