非静态成员函数作为线程函数

如题,下面是代码.

 1 // header.h
 2 class A
 3 {
 4 public:
 5     bool StartServer(int port);
 6 
 7 private:
 8     unsigned int __stdcall listenThreadFunction();
 9     
10     int mData;
11 }
12 
13 // implement.cpp
14 #include "header.h"
15 
16 union
17 {
18     unsigned int (__stdcall *ThreadPorc)(void*);
19     unsigned int (__stdcall A::*MemberProc)();
20 }StdcallProc;
21 
22 bool A::StartServer(int port)
23 {
24     mData = 100;    // 测试
25 
26     StdcallProc.MemberProc = &A::listenThreadFunction;        // 关键点,将"非静态成员函数"放进去了
27     // ...
28     // 注意作为线程的非静态成员函数是没有参数的,因为非静态成员函数有一个默认的this参数
29     // 即,函数参数列表为空的非静态成员函数已经有了一个参数,那就在创建线程的时候将this作为参数值传入即可.
30     CloseHandle((HANDLE)_beginthreadex(NULL, 0, StdcallProc.ThreadPorc, (void*)this, 0, NULL));
31     // ...    
32 }
33 
34 unsigned int A::listenThreadFunction()
35 {
36     // 这是线程函数.
37     // 在这里可以使用this指针啦.
38     
39     // 在这里可以正常输出mData的值:100.
40     std::cout << mData << std::endl;
41     
42     return 0;
43 }

 

posted @ 2013-03-15 08:21  莫压枯枯地  阅读(1805)  评论(0编辑  收藏  举报