#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;
}
what i want is to make sure everytime there is a customer thread to get an increased global, expect display like: 1, 2, 3, ..., but what i see is the global value will be increased between wait and activity--, thus, actual display is: 1, 23, 56, 78, ....
I've found out the problem is in wait(), acutully there are 3 steps in wait(), 'unlock, wait, lock', between signaled(wait return) and mutex.lock, it's not a atomic operation, the producer thread may lock mutex before wait() to lock mutex, and the activity is still not zero, so the global will increased, unexpectedly
is there a way to make sure what i expect?