大家好,有个疑问:在主线程中创建一个事件,接着在派生的一个线程中关闭这个事件,然后让另一个派生的线程去永久等待这个事件,那么会得到什么结果呢?
我认为应该是WaitForSingleObject立即返回WAIT_FAILED,错误码为非法句柄。但事实上没有确定的结果,试了十次左右,9次是一直等待,1次是立即返回WAIT_FAILED。代码如下:
string protect_type;
HANDLE protect_handle;
HANDLE threads_handle[2];DWORD WINAPI wait_thread (void *lpParam)
{
DWORD ret = WaitForSingleObject (protect_handle, INFINITE);
if (ret == WAIT_OBJECT_0){
cout << "得到了锁" << endl;
}else if (ret == WAIT_ABANDONED){
cout << "锁被抛弃了" << endl;
}else if (ret == WAIT_FAILED){
cout << "等待出错," << GetLastError () << endl;
}
return 0;
}DWORD WINAPI acquire_thread (void *lpParam)
{
if (protect_type == "mutex"){
WaitForSingleObject (protect_handle, INFINITE);
ResumeThread (threads_handle[1]);
return 0;
}else if (protect_type == "event"){
bool ret = CloseHandle (protect_handle);
ResumeThread (threads_handle[1]);
return 0;
}else
return -1;
}void test_wait ()
{
//protect_type = "mutex";
//protect_handle = CreateMutex (NULL, false, 0);
protect_type = "event";
protect_handle = CreateEvent (NULL, true, false, 0);
threads_handle[0] = CreateThread (NULL, 0, acquire_thread, 0, CREATE_SUSPENDED, 0);
threads_handle[1] = CreateThread (NULL, 0, wait_thread, 0, CREATE_SUSPENDED, 0);
ResumeThread (threads_handle[0]);
WaitForMultipleObjects (2, threads_handle, TRUE, INFINITE);
}int main ()
{
test_wait ();
}
我认为应该是WaitForSingleObject立即返回WAIT_FAILED,错误码为非法句柄。但事实上没有确定的结果,试了十次左右,9次是一直等待,1次是立即返回WAIT_FAILED。代码如下:
string protect_type;
HANDLE protect_handle;
HANDLE threads_handle[2];DWORD WINAPI wait_thread (void *lpParam)
{
DWORD ret = WaitForSingleObject (protect_handle, INFINITE);
if (ret == WAIT_OBJECT_0){
cout << "得到了锁" << endl;
}else if (ret == WAIT_ABANDONED){
cout << "锁被抛弃了" << endl;
}else if (ret == WAIT_FAILED){
cout << "等待出错," << GetLastError () << endl;
}
return 0;
}DWORD WINAPI acquire_thread (void *lpParam)
{
if (protect_type == "mutex"){
WaitForSingleObject (protect_handle, INFINITE);
ResumeThread (threads_handle[1]);
return 0;
}else if (protect_type == "event"){
bool ret = CloseHandle (protect_handle);
ResumeThread (threads_handle[1]);
return 0;
}else
return -1;
}void test_wait ()
{
//protect_type = "mutex";
//protect_handle = CreateMutex (NULL, false, 0);
protect_type = "event";
protect_handle = CreateEvent (NULL, true, false, 0);
threads_handle[0] = CreateThread (NULL, 0, acquire_thread, 0, CREATE_SUSPENDED, 0);
threads_handle[1] = CreateThread (NULL, 0, wait_thread, 0, CREATE_SUSPENDED, 0);
ResumeThread (threads_handle[0]);
WaitForMultipleObjects (2, threads_handle, TRUE, INFINITE);
}int main ()
{
test_wait ();
}
另一方面,Sleep应该加在哪呢?请赐教。
在线程启动后立即sleep,确保事件已经关闭后,再wait