race condition

How do i simulate race condition ?

I made 2 functions, func2 and func3.

func2 waits for 10 sec and then add one to a value.

func3 executes immediately and multiplies the value by 2.

I used d = 2 as a starting value. Since the thread for func3 executes faster as , i would the result to print
" the value of d is " 4 ;

then it should print

"the value of d is " 3,

but it actually prints

" the value of d is " 4;
" the value of d is " 4

does this simulate race condition by commenting out the t8.join() and t9.join() ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

#include <iostream>
#include <string>
#include <functional>
#include <windows.h>
#include <thread>
#include <future>



// passes value by reference
int func2(int & a)
{

	Sleep(10000);

	++a;

	return a;
}



// passes value by reference
int func3(int & a)
{
	a *= 2 ;

	return a;
}


int main()
{

int d = 2;

thread t8(func2, ref(d));   // 2 + 1 = 3 

thread t9(func3, ref(d));  // 2 * 2 = 4 
//t9.join();
cout << "the value of d from func3 is " << d << endl; //should print 4

//t8.join();
cout << "the value of d from func2 is " << d << endl;  // should print 3 


}
  
Last edited on
then it should print

"the value of d is " 3,


Why would it ever print that? The value of d is never 3 in this code.

The variable starts with the value 2, that gets doubled to 4, and if the program is still running ten seconds later it will become 5. It is never 3.
does this simulate race condition by commenting out the t8.join() and t9.join() ?
No, you need join, otherwise the program may end before even a single thread is started.

You simulate race condition when you sleep(...) randomly in both threads.
Pedantic note: You're not simulating a race condition, because one actually exists (well, you're trying to make one exist, at least), if we're dealing with actual threads. Because it's actually happening. Sleeps can help contrive a race condition easier when debugging.
Last edited on
Topic archived. No new replies allowed.