On follow link (http://www.cplusplus.com/reference/mutex/mutex/try_lock/) we have declared that sample can return only values from 1 to 100000. Does it is declared that 0 can't be in output?
// mutex::try_lock example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
volatile int counter (0); // non-atomic counter
std::mutex mtx; // locks access to counter
void attempt_10k_increases () {
for (int i=0; i<10000; ++i) {
if (mtx.try_lock()) { // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(attempt_10k_increases);
for (auto& th : threads) th.join();
std::cout << counter << " successful increases of the counter.\n";
return 0;
}
In any case, it's easy to answer 'How to get 2?', but really not clear about how to get 1 and never get 0.
The try_lock can "fail spuriously when no other thread has a lock on the mutex, but repeated calls in these circumstances shall succeed at some point", but if it true, then sample can return 0 (and also can return 1 in some case).
But, if this specification sample declared true and 0 cannot be in output, then words about "fail spuriously" maybe not true then?