我很惊讶奇怪的异常,我得到了。C++类:创建线程+指向函数的指针=访问冲突
class Threads {
public:
Threads() {}
~Threads() {}
void StartThread(int (*p)()); //pointer to a function
private:
HANDLE hThread;
DWORD dwThreadID;
};
方法StartThread应接收指向我的函数(将在另一个线程中运行)的指针。
这个功能很简单。 (你可以看到它位于类主题外):
int MyThread()
{
return 0;
}
这是创建线程的方法:
inline void Threads::StartThread(int (*p)())
{
hThread = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)(*p)(),
NULL,
0,
&dwThreadID);
if (hThread == NULL)
{
return;
}
}
这里编译得到错误:无法从“诠释”转换参数3 'LPTHREAD_START_ROUTINE'。那就是为什么我做了这个演员。
在主函数中,我创建了Threads类型的对象,并尝试调用方法StartThread。作为参数I发送指向函数MyThread的指针。
Threads *thread1;
thread1 = new Threads();
thread1->StartThread(MyThread);
我以为MyThread必须在另一个线程中启动。但函数MyTread总是在主线程中运行!!!只有在MyThread结束后,另一个线程才会启动,然后出现以下异常: ThreadClass.exe中0x00000000处未处理的异常:0xC0000005:访问冲突。
我需要聪明的建议!
这已被问了很多次之前:http://stackoverflow.com/questions/1372967/how-to-use-createthread-for-functions-which-are-class-members http://stackoverflow.com/ question/2891926/create-thread-is-not-accepting-the-member-functon http://stackoverflow.com/questions/402992/passing-function-pointers-in-c http://stackoverflow.com/questions/ 7140042/c-functor-as-a-function-pointer http://stackoverflow.com/questions/4681581/how-do-i-call-worker-thread-in-a-same-class-c-mfc http: //stackoverflow.com/questions/4666635/run-threads-of-class-member-function-in-c仅举几例 –