在C语言下面,创建多线程不是很复杂,直接调用win32的CreateThread函数就可以了。但是怎么用C++创建多线程确实是一个问题。一方面,创建线程中的函数指针不能是成员函数,一方面我们希望可以把成员函数当作是线程的入口函数,这中间应该怎么调和呢?
我想,要想做到这一点可以充分利用C++语言的两个特性,一个是this指针,一个就是静态函数。利用this指针可以传递入口参数,而静态函数解决的是入口地址的问题。如果再加上C++的多态特性,那就更加完美了。
下面的代码是我个人的想法和思路,欢迎多提宝贵意见。
#include <stdio.h> #include <windows.h> class data{ public: data() {} virtual ~data() {} virtual void run() { printf("this is data!\n");} static unsigned long __stdcall func(void* param){ ((class data*)(param))->run(); return 1; } void create_thread(){ CreateThread(NULL, 0, data::func, this, 0, NULL); } }; class test: public data{ public: test() {} ~test() {} void run() {printf("this is test!\n");} }; int main(int argc, char* argv[]) { data d, *p; test t; p = &d; p->create_thread(); p = &t; p->create_thread(); while(1) Sleep(100); return 1; } |