深入浅出Win32多线程程序设计之线程控制
网址:http://soft./lesson/36/
WIN32线程控制主要实现线程的创建、终止、挂起和恢复等操作,这些操作都依赖于WIN32提供的一组API和具体编译器的C运行时库函数。
在启动一个线程之前,必须为线程编写一个全局的线程函数,这个线程函数接受一个32位的LPVOID作为参数,返回一个UINT,线程函数的结构为:
UINT ThreadFunction(LPVOID pParam)
{
//线程处理代码
return0;
}
在线程处理代码部分通常包括一个死循环,该循环中先等待某事情的发生,再处理相关的工作:
while(1)
{
WaitForSingleObject(…,…);//或WaitForMultipleObjects(…)
//Do something
}
一般来说,C++的类成员函数不能作为线程函数。这是因为在类中定义的成员函数,编译器会给其加上this指针。请看下列程序:
#include ""
#include <>
class ExampleTask
{
public:
void taskmain(LPVOID param);
void StartTask();
};
void ExampleTask::taskmain(LPVOID param)
{}
void ExampleTask::StartTask()
{
_beginthread(taskmain,0,NULL);
}
int main(int argc, char* argv[])
{
ExampleTask realTimeTask;
();
return 0;
}
程序编译时出现如下错误:
error C2664: '_beginthread' : cannot convert parameter 1 from 'void (void *)' to 'void (__cdecl *)(void *)'
None of the functions with this name in scope match the target type
再看下列程序:
#include ""
#include <>
class ExampleTask
{
public:
void taskmain(LPVOID param);
};
void ExampleTask::taskmain(LPVOID param)
{}
int main(int argc, char* argv[])
{
ExampleTask realTimeTask;
_beginthread(ExampleTask::taskmain,0,NULL);
return 0;
}
程序编译时会出错:
error C2664: '_beginthread' : cannot convert parameter 1 from 'void (void *)' to 'void (__cdecl *)(void *)'
None of the functions with this name in scope match the target type
如果一定要以类成员函数作为线程函数,通常有如下解决方案:
(1)将该成员函数声明为static类型,去掉this指针;
我们将上述二个程序改变为:
#include ""
#include <>
class ExampleTask
{
public:
void static taskmain(LPVOID param);
void StartTask();
};
void ExampleTask::taskmain(LPVOID param)
{}
void ExampleTask::StartTask()
{
_beginthread(taskmain,0,NULL);
}
int main(int argc, char* argv[])
{
ExampleTask realTimeTask;
();
return 0;
}
和
#include "
线程控制 来自淘豆网www.taodocs.com转载请标明出处.