现在的位置: 首页 > 综合 > 正文

多线程调用类的成员函数的实现

2013年05月27日 ⁄ 综合 ⁄ 共 902字 ⁄ 字号 评论关闭

该方法实现了多线程灵活的调用类的成员函数。代码如下:

#include <stdio.h>
#include <pthread.h>
#include <iostream>
//g++ -lpthread -o cpro cpro.cpp
class triangle
{
	private:
		int length;
		int width;
		int height;


	public:
		triangle();
		virtual ~triangle();
		static void displayFirst(triangle *pthis);
		void display();
		void show();
};


triangle::triangle()
{
	length = 2;
	width  = 3;
	height = 4;
}
void triangle::display()
{
	printf("%d,%d,%d\n",length,width,height);
}
void triangle::show()
{
	printf("My name is tianmo,I am from Hust.\n");
}
void triangle::displayFirst(triangle *pthis)
{
	pthis->display();
}
triangle::~triangle()
{
}

struct A
{
	triangle *p; //类对象指针
	void (triangle::*pmf)();//成员函数指针
};


void *midCall(void *ptr)
{	
	A *pa = (A*)ptr;//强制转换 void* 为 A*

	triangle *ph = pa->p;//从A中析取triangle类对象地址
	
	void (triangle::*pmf)() = pa->pmf;//析取ptr到成员函数
	
	(ph->*pmf)();//调用成员函数
}
int main()
{
	A a;//结构实例
	triangle h;//创建对象
	//填充结构
	a.p = &h; 
	a.pmf = &triangle::display; //取成员函数地址

	pthread_t id;		
	pthread_create(&id,NULL,midCall,(void *)&a);
	pthread_join(id,NULL);

	return 0;
}

抱歉!评论已关闭.