I was expecting that if timed_mutex.try_lock_for could success for all calling threads, like this:
timed_mutex tm;
atomic<int> atTm(0);
void tTMutex(int i) {
this_thread::sleep_for(chrono::microseconds(200 * i));
if (tm.try_lock_for(chrono::milliseconds(200 * i))) {
atTm.fetch_add(1);
}
}
int main() {
thread t[3];
for (size_t i = 0; i < size(t); ++i) {
t[i] = thread(tTMutex, i);
}
ready = true;
for (size_t i = 0; i < size(t); ++i) {
t[i].join(); // seems only 1 thread increased atTm
}
cout << atTm;
return 0;
}
It prints "1", while I expected that it could print "3". As long as 3 threads call tm.try_lock_for in different time, I think they should all successfully return, but in fact not: what's the reason for this?
I changed my program slightly, using ordinary mutex instead of timed_mutex, as below:
mutex mAllWait; // change 1
atomic<int> atAll(0);
void tMutex() {
unique_lock<mutex> lk(mAllWait); // change 2
this_thread::sleep_for(chrono::milliseconds(200));
atAll.fetch_add(1);
}
int main() {
thread t[3];
for (size_t i = 0; i < size(t); ++i) {
t[i] = thread(tMutex);
}
ready = true;
for (size_t i = 0; i < size(t); ++i) {
t[i].join(); // all threads can increase atAll
}
cout << atAll;
return 0;
}
It prints 3, as I expected. So what's the core difference between the 2 programs?