我编写了一些像这样的测试代码,它编译并运行良好......
void threadtest()
{
HANDLE hThrd;
DWORD threadId;
int i;
for (i = 0;i < 5;i++)
{
hThrd = CreateThread(
NULL,
0,
ThreadFunc,
(LPVOID)i,
0,
&threadId );
}
// more stuff
}
DWORD WINAPI ThreadFunc(LPVOID n)
{
// stuff
return 0;
}
然后我想修改代码以将 ThreadFunc 放入一个类中,然后声明这些类的数组。我认为代码应该如下所示:
class thread_type
{
public:
DWORD WINAPI ThreadFunc(LPVOID n)
{
// stuff
return 0;
}
};
void threadtest()
{
HANDLE hThrd;
DWORD threadId;
int i;
thread_type *slave;
slave = new thread_type[5];
for (i = 0;i < 5;i++)
{
hThrd = CreateThread(
NULL,
0,
slave[i].ThreadFunc,
(LPVOID)i,
0,
&threadId );
}
// more stuff
}
不幸的是,编译器提示行slave[i].ThreadFunc,我想我可能需要一些特殊的转换,但我尝试的所有涉及“::”和“&”的排列似乎都失败了(我对C++)。真实的代码有一些额外的复杂性,为了清楚起见,我没有包括这些复杂性,但我认为它们是无关紧要的。
最佳答案
代码的第一个问题是测试类不是 thread_type 的后代。您需要以某种方式指定基类。 其次,如果您传递函数指针,则不应该是 thiscall 类型。解决方案通常是这样的:
struct thread
{
virtual void
run() = 0;
static thread_func(void* param)
{
thread* pThread = (thread*)param;
thread->run();
}
}
struct worker : public thread
{
void
run()
{
(.. code for the thread...)
}
}
void threadtest()
{
HANDLE hThrd;
DWORD threadId;
int i;
thread *slave;
slave = new thread_type[5];
slave[0] = new worker;
slave[1] = new worker;
slave[2] = new worker;
slave[3] = new worker;
slave[4] = new worker;
for (i = 0;i < 5;i++)
{
hThrd = CreateThread(
NULL,
0,
&thread::thread_func,
(LPVOID)slave[i],
0,
&threadId );
}
// more stuff
}
请注意,这可能只是一个反射,我现在无法编译,因为我这里没有任何东西可以这样做,但逻辑应该是这样的。
关于c++ - LPTHREAD_START_ROUTINE/类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1477239/