Windows的CONDITION_VARIABLE使用CRITICAL_SECTION时,代码如下
#include <Windows.h>
#include <iostream>
#include <thread>
#include <vector>
int Test(CONDITION_VARIABLE &cv, CRITICAL_SECTION &cs)
{
EnterCriticalSection(&cs);
SleepConditionVariableCS(&cv, &cs, INFINITE);
std::cout << std::this_thread::get_id() << std::endl;
LeaveCriticalSection(&cs);
return 0;
}
int main()
{
CONDITION_VARIABLE cv;
InitializeConditionVariable(&cv);
CRITICAL_SECTION cs;
InitializeCriticalSection(&cs);
std::vector<std::thread> vec_threads;
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
vec_threads.emplace_back(Test, std::ref(cv), std::ref(cs));
// 等待所有线程都已经处在等待条件变量的状态
std::this_thread::sleep_for(std::chr