-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTest&Set_Code.txt
60 lines (44 loc) · 1.18 KB
/
Test&Set_Code.txt
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
50
51
52
53
54
55
56
57
58
59
// Test-and-Set.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <thread>
using namespace std;
bool lock_1 = false;
int shared_resource = 0;
bool Test_and_Set(bool* key);
void process_1();
void process_2();
int main()
{
int x;
thread thread_1 = thread(process_1);
thread thread_2 = thread(process_2);
thread_2.join();
thread_1.join();
cout << shared_resource << endl;
cin >> x;
}
bool Test_and_Set(bool* key)
{
bool x = *key;
*key = true;
return x;
}
void process_1()
{
while (Test_and_Set(&lock_1)) cout << "Process(1) is stuck !! " << endl; //do nothing
cout << "Process(1) starts its execution " << endl;
shared_resource += 2;
//PIECE OF CODE
cout << "Process(1) release the lock !! " << endl;
lock_1 = false; //release the shared resource
}
void process_2()
{
while (Test_and_Set(&lock_1)) cout << "Process 2 is stuck !!"<<endl; //do nothing
cout << "Process(2) starts its execution " << endl;
shared_resource = 10;
//PIECE OF CODE
cout << "Process(2) release the lock !! " << endl;
lock_1 = false; //release the shared resource
}