我很驚訝奇怪的異常,我得到了。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僅舉幾例 –