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

20th Nov 2024, 7:12 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Respostas
+ 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
21st Nov 2024, 12:53 AM
Bob_Li
Bob_Li - avatar
+ 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
21st Nov 2024, 4:15 AM
Bob_Li
Bob_Li - avatar
+ 1
Thanks Bob_Li. Will go through it. Many thanks again!
21st Nov 2024, 6:20 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
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
21st Nov 2024, 4:07 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
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;
21st Nov 2024, 6:47 PM
Ketan Lalcheta
Ketan Lalcheta - avatar