作者rosemary0401 (rosemary0401)
看板C_and_CPP
標題[問題] _beginthread 後,使用 CloseHandle 出現錯誤
時間Mon Nov 29 14:55:49 2010
仿照網路上找到的範例,練習寫thread
程式碼如下:
#include <iostream>
#include <windows.h>
#include <process.h>
#define THREAD_COUNT 2
using namespace std;
int g_num = 0;
void ThreadVariable1(void* argu)
{
Sleep(3000);
g_num = 100;
_endthread();
}
void ThreadVariable2(void* argu)
{
Sleep(3000);
g_num = 50;
_endthread();
}
void main()
{
HANDLE threadArray[THREAD_COUNT];
threadArray[0] = (HANDLE) _beginthread(ThreadVariable1, 0, NULL);
threadArray[1] = (HANDLE) _beginthread(ThreadVariable2, 0, NULL);
WaitForMultipleObjects(THREAD_COUNT, threadArray, TRUE, INFINITE);
printf("%d\n", g_num);
CloseHandle(threadArray[0]);
CloseHandle(threadArray[1]);
cin.get();
}
編譯會過,但是執行會出現錯誤如下:
First-chance exception at 0x772d5e4f in simpleThreadTest2.exe: 0xC0000008: An
invalid handle was specified.
為什麼呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 111.240.230.37
→ stupid0319:我建議是執行緒自己結束比較好,不要外部強迫結束 11/29 15:14
→ rosemary0401:是喔 為什麼呢? 11/29 15:24
→ stupid0319:你用的WaitForMultipleObjects好像少了點什麼 11/29 15:33