#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
std::mutex globalMutex;
std::condition_variable globalCondition;
int global = 0;
int activity = 0;
int CountOfThread = 1; // or more than 1
// just for console display, not effect the problem
std::mutex consoleMutex;
void producer() {
while (true) {
{
std::unique_lock<std::mutex> lock(globalMutex);
while (activity == 0) {
lock.unlock();
std::this_thread::yield();
lock.lock();
}
global++;
globalCondition.notify_one();
}
std::this_thread::yield();
}
}
void customer() {
while (true) {
int x;
{
std::unique_lock<std::mutex> lock(globalMutex);
activity++;
globalCondition.wait(lock); // <- problem
activity--;
x = global;
}
{
std::lock_guard<std::mutex> lock(consoleMutex);
std::cout << x << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i < CountOfThread; ++i) {
std::thread(customer).detach();
}
std::thread(producer).detach();
getchar();
return 0;
}
我想是確保每次有客戶線程獲得一個全球性增加,預計像顯示:1,2,3,......,但我看到的是在等待和活動之間會增加全局值 - 因此,實際顯示爲:1,23,56,78,...C++:條件變量等待
我已經發現問題出在wait(),acutully there在wait(),'unlock,wait,lock'之間的3個步驟,在signaled(wait return)和mutex.lock之間,它不是原子操作,生產者線程可能在wait()鎖定互斥之前鎖定互斥,仍然不爲零,所以全球意外增加,意外
有沒有辦法確定我的期望?
祝賀。它幫助極大! –