[英]How can I begin thread in windows using functor as thread function without using C++11 thread?
I'm writing a simple thread lib for Windows. 我正在为Windows编写一个简单的线程库。 I want to pass this functor
我想通过这个函子
struct callable
{
void operator()()
{
for(int i = 0; ;++i)
{
std::cout << i << std::endl;
}
}
};
In _beginthread()
this way: 在
_beginthread()
这种方式:
int main()
{
callable c;
_beginthread(c, 0, 0);
}
but it's not possible. 但这是不可能的。 The ability to pass functor in the thread is very necessary for my library.
对于我的库,在线程中传递函子的功能非常必要。 I know that
boost::thread
provides this ability, thus it is possible. 我知道
boost::thread
提供了此功能,因此是可能的。 How can I begin thread in windows using functor as thread function without using C++11 thread? 如何在不使用C ++ 11线程的情况下使用functor作为线程函数在Windows中开始线程?
[upd] without using C++11 thread [upd]不使用C ++ 11线程
The standard technique is as follows: 标准技术如下:
CreateThread
passing a suitable thread proc (more later), and the address of your struct in the lpParameter
parameter. CreateThread
并传递适当的线程proc(稍后再介绍),并在lpParameter
参数中提供结构的地址。 lpParameter
. lpParameter
中传递该结构的地址。 The thread proc looks like this: 线程proc如下所示:
DWORD WINAPI ThreadProc(void *lpParameter)
{
callable *c = (callable*)lpParameter;
(*c)();
delete c;
return 0;
}
And the call to CreateThread
is along these lines: 对
CreateThread
的调用遵循以下CreateThread
行:
callable *c = new callable;
// initialise c
CreateThread(NULL, 0, ThreadProc, (void*)c, 0, &threadID);
I apologise if there are syntax errors here, I'm not at all fluent in C++. 我很抱歉如果这里有语法错误,我一点也不精通C ++。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.