0
Odd even threads without condition variable
Hi Refer code version 2 which asks threads to print odd and even value one by one using condition variable. It works fine and I belive it is good (feel free to share your view if there is any improvement) I was asked to implement it without condition variable. I tried without condition variable and only using mutex as below (code version 1) but it fails. Please suggest. https://sololearn.com/compiler-playground/cQCvnPULVKxD/?ref=app https://sololearn.com/compiler-playground/cYsd3zJciORH/?ref=app
6 Antworten
+ 1
it seems to be working fine for both. code 2 just happen to output alternately while code 1 outputs them by thread.
Maybe what is missing in code 1 is thread synchronization, like what you have in code 2
https://www.geeksforgeeks.org/thread-synchronization-in-cpp/
https://chrizog.com/cpp-thread-synchronization
+ 1
odd even thread 1 is normal thread behavior. which thread gets run is determined by the os. No synchronization mechanism here.
odd even thread 2 have the thread execution synchronized by condition_variable cv and bool isOddTurn.
here is an SO topic related to your question. It have a lot of clever solutions
https://stackoverflow.com/questions/14641134/printing-odd-and-even-number-printing-alternately-using-threads-in-c
I modified one of the answers into the code below:
one function version:
https://sololearn.com/compiler-playground/crwYlot7C6m3/?ref=app
two function version: use unique_lock instead of lock_guard, and an external boolean flag for state checking.
https://sololearn.com/compiler-playground/cyjlF2FtkBEK/?ref=app
+ 1
Thanks Bob_Li. Will go through it. Many thanks again!
0
Thanks Bob_Li
I belive both 1 and 2 are having synchronization implemented. Just curious why 1 i.e. without condition variable is not printing only thread wise
0
Seems something is wrong in one function version.
Getting inconsistent behavior when num and endvalue is changed to below values:
const int num = 40;
const int endValue = 100;
0
maybe there's a limit? Other processes are also using their own threads, so how many is actually available to use could be quite low. You can set a higher number, but it would not necessarily be better. Best not to go crazy with it.
const int num = thread::hardware_concurrency();
cout << num << endl;