CPP
cpp
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
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
using namespace std;
// Mutexes for protecting the global variables (g_var1 and g_var2)
mutex g_m1;
mutex g_m2;
// Global variables (shared by all threads, but protected by mutexes)
int g_var1;
int g_var2;
// Global thread-local variable: Each thread gets its OWN copy of gt_var
thread_local int gt_var = 0; // Initialized to 0 for clarity
// Function executed by the first set of threads
void test1() {
// Lock the mutex to protect access to g_var1
lock_guard<mutex> lg(g_m1);
// Increment and print g_var1 and its address
cout << ++g_var1 << " " << &g_var1 << " ";
// Increment and print gt_var (each thread will have its own independent value) and its address
cout << ++gt_var << " " << >_var << endl;
}
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run