http://blog.youkuaiyun.com/aguiwang/article/details/6937243
线程的入口函数种类大致如下:
在C程序当中线程的入口函数就是全局函数,这种方式也可以在C++里面继续延用。在C++里面还有其它形式的函数可以作为线程的入口函数,相对而且比C的全局函数更符合封装的思想。下面我们一一介绍:
一、全局函数作为线程的入口函数:可以通过传递对象的this指针来实现访问对象的public成员
- unsigned ThreadFunc(void* lparam);)//全局函数
- class CThread
- {
- public:
- CThread(int i,int y):m_i(i),m_y(y)
- {
- };
- void StartThread();
- m_y;
- protected:
- int m_i;
- };
- void CThread::StartThread()
- {
- AfxBeginThread(ThreadFunc,this);
- }
- unsigned ThreadFunc(void* lparam)//全局函数
- {
- CThread* pthr = (CThread*)lparam;
- for(int i = 0;i<10;i++)
- {
- std::cout<<i+pthr->m_i<<std::endl;//访问公有有成员
- //std::cout<<i+pthr->m_y<<std::endl;//不能访问私有成员
- Sleep(100);
- }
- return 0;
- };
- int main(int argc, char * argv[])
- {
- CThread thread(1,2);
- thread.StartThread();
- return 0;
- }
二、友元函数作为线程的入口函数:它的调用和传递机制跟C的全局函数是一样的。
- class CThread
- {
- public:
- CThread(int i,int y):m_i(i),m_y(y)
- {
- };
- void StartThread();
- friend unsigned ThreadFunc(void* lparam);
- m_y;
- protected:
- int m_i;
- };
- void CThread::StartThread()
- {
- AfxBeginThread(ThreadFunc,this);
- }
- unsigned ThreadFunc(void* lparam)
- {
- CThread* pthr = (CThread*)lparam;
- for(int i = 0;i<10;i++)
- {
- std::cout<<i+pthr->m_i<<std::endl;
- std::cout<<i+pthr->m_y<<std::endl;//访问私有成员
- Sleep(100);
- }
- return 0;
- };
- int main(int argc, char * argv[])
- {
- CThread thread(1,2);
- thread.StartThread();
- return 0;
- }
友元函数比全局函数更加高效而强悍(能访问类的所有成员),但是以破坏类的封装性为代价的。
三、静态成员函数作为线程的成员函数:它对外可以是public也可以是private,它的优点就是没有破坏类的封装性。但它只能访问类的静态成员,当然这点可以通过给它的参数传递对象的this指针来克服,但这样也不能访问对象的public以外的成员。
- class CThread
- {
- public:
- CThread(int i,int y):m_i(i),m_y(y)
- {
- };
- void StartThread();
- static unsigned ThreadFunc(void* lparam);
- m_y;
- protected:
- int m_i;
- };
- void CThread::StartThread()
- {
- AfxBeginThread(ThreadFunc,this);
- }
- unsigned CThread::ThreadFunc(void* lparam)
- {
- CThread* pthr = (CThread*)lparam;
- for(int i = 0;i<10;i++)
- {
- std::cout<<i+pthr->m_i<<std::endl;
- //std::cout<<i+pthr->m_y<<std::endl;//不能访问私有成员
- Sleep(100);
- }
- return 0;
- };
- int main(int argc, char * argv[])
- {
- CThread thread(1,2);
- thread.StartThread();
- return 0;
- }
四、普通成员函数作为线程入口函数:这种方式能突破上述方法的局限,即不破坏类的封装性,能访问对象的所以成员,可以是虚函数,能实现多态
class CThread
{
public:
DWORD WINAPI ThreadFunc(LPVOID param);
...
};
有如上类,在类中某函数想以函数ThreadFunc最为线程入口函数:
CreateThread(NULL, 0, WorkThread, ¶m, 0, &ThreadID))
编译会报错:cannot convert parameter 3 from unsigned long (void *) to unsigned long (__stdcall *)(void *) None of the functions with this name in scope match the target type
怎么解决这个问题,详解:http://blog.youkuaiyun.com/aguiwang/article/details/6941596