我在理解 winapi 条件变量如何工作时遇到问题。
在更具体的方面,我想要的是几个线程在某些条件下等待。然后我想使用 WakeAllConditionVariable() 调用来唤醒所有线程,以便它们可以工作。除了我只想启动线程这一事实之外,它们没有任何其他先决条件可以开始工作(就像您在 n 生产者/ n 消费者场景中那样)。
这是到目前为止的代码:
#define MAX_THREADS 4
CONDITION_VARIABLE start_condition;
SRWLOCK cond_rwlock;
bool wake_all;
__int64 start_times[MAX_THREADS];
主线程:
int main()
{
HANDLE h_threads[ MAX_THREADS ];
int tc;
for (tc = 0; tc < MAX_THREADS; tc++)
{
DWORD tid;
h_threads[tc] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)thread_routine,(void*)tc,0,&tid);
if( h_threads[tc] == NULL )
{
cout << "Error while creating thread with index " << tc << endl;
continue;
}
}
InitializeSRWLock( &cond_rwlock );
InitializeConditionVariable( &start_condition );
AcquireSRWLockExclusive( &cond_rwlock );
// set the flag to true, then wake all threads
wake_all = true;
WakeAllConditionVariable( &start_condition );
ReleaseSRWLockExclusive( &cond_rwlock );
WaitForMultipleObjects( tc, h_threads, TRUE, INFINITE );
return 0;
}
这是线程例程的代码:
DWORD thread_routine( PVOID p_param )
{
int t_index = (int)(p_param);
AcquireSRWLockShared( &cond_rwlock );
// main thread sets wake_all to true and calls WakeAllConditionVariable()
// so this thread should start doing the work (?)
while ( !wake_all )
SleepConditionVariableSRW( &start_condition,&cond_rwlock, INFINITE,CONDITION_VARIABLE_LOCKMODE_SHARED );
QueryPerformanceCounter((LARGE_INTEGER*)&start_times[t_index]);
// do the actual thread related work here
return 0;
}
这段代码没有做我期望它做的事情。有时只有一个线程完成工作,有时两个或三个,但绝不会全部完成。主函数永远不会通过 WaitForMultipleObjects() 调用。
我不确定我做错了什么,但我会在某处假设一些同步问题?
任何帮助,将不胜感激。(对不起,如果我用不同的着装重新发布了旧主题:)