1*a44af2ecSJérôme Duval /*
2*a44af2ecSJérôme Duval * Copyright 2021, Jérôme Duval, jerome.duval@gmail.com.
3*a44af2ecSJérôme Duval * Distributed under the terms of the MIT License.
4*a44af2ecSJérôme Duval */
5*a44af2ecSJérôme Duval #include <stdio.h>
6*a44af2ecSJérôme Duval #include <stdlib.h>
7*a44af2ecSJérôme Duval #include <unistd.h>
8*a44af2ecSJérôme Duval #include <pthread.h>
9*a44af2ecSJérôme Duval #include <thread>
10*a44af2ecSJérôme Duval
11*a44af2ecSJérôme Duval #define CYCLES 2
12*a44af2ecSJérôme Duval
13*a44af2ecSJérôme Duval
14*a44af2ecSJérôme Duval class MyClass
15*a44af2ecSJérôme Duval {
16*a44af2ecSJérôme Duval public:
MyClass()17*a44af2ecSJérôme Duval MyClass() { i=0; printf("MyClass() called() %p\n", this); }
~MyClass()18*a44af2ecSJérôme Duval ~MyClass() { printf("~MyClass() called() %d %p\n", i, this); }
19*a44af2ecSJérôme Duval
Touch()20*a44af2ecSJérôme Duval void Touch() { i++; printf("Touch() called() %d %p\n", i, this); }
21*a44af2ecSJérôme Duval
22*a44af2ecSJérôme Duval private:
23*a44af2ecSJérôme Duval int j;
24*a44af2ecSJérôme Duval int i;
25*a44af2ecSJérôme Duval };
26*a44af2ecSJérôme Duval
27*a44af2ecSJérôme Duval thread_local MyClass myClass1;
28*a44af2ecSJérôme Duval thread_local MyClass myClass2;
29*a44af2ecSJérôme Duval
threadFn(void * id_ptr)30*a44af2ecSJérôme Duval void* threadFn(void* id_ptr)
31*a44af2ecSJérôme Duval {
32*a44af2ecSJérôme Duval int thread_id = *(int*)id_ptr;
33*a44af2ecSJérôme Duval
34*a44af2ecSJérôme Duval for (int i = 0; i < CYCLES; ++i) {
35*a44af2ecSJérôme Duval int wait_sec = 1;
36*a44af2ecSJérôme Duval sleep(wait_sec);
37*a44af2ecSJérôme Duval myClass1.Touch();
38*a44af2ecSJérôme Duval myClass2.Touch();
39*a44af2ecSJérôme Duval }
40*a44af2ecSJérôme Duval
41*a44af2ecSJérôme Duval return NULL;
42*a44af2ecSJérôme Duval }
43*a44af2ecSJérôme Duval
44*a44af2ecSJérôme Duval
thread_local_test(int count)45*a44af2ecSJérôme Duval int thread_local_test(int count)
46*a44af2ecSJérôme Duval {
47*a44af2ecSJérôme Duval pthread_t ids[count];
48*a44af2ecSJérôme Duval int short_ids[count];
49*a44af2ecSJérôme Duval
50*a44af2ecSJérôme Duval srand(time(NULL));
51*a44af2ecSJérôme Duval
52*a44af2ecSJérôme Duval for (int i = 0; i < count; i++) {
53*a44af2ecSJérôme Duval short_ids[i] = i;
54*a44af2ecSJérôme Duval pthread_create(&ids[i], NULL, threadFn, &short_ids[i]);
55*a44af2ecSJérôme Duval }
56*a44af2ecSJérôme Duval
57*a44af2ecSJérôme Duval for (int i = 0; i < count; i++)
58*a44af2ecSJérôme Duval pthread_join(ids[i], NULL);
59*a44af2ecSJérôme Duval
60*a44af2ecSJérôme Duval return 0;
61*a44af2ecSJérôme Duval }
62*a44af2ecSJérôme Duval
63*a44af2ecSJérôme Duval
main()64*a44af2ecSJérôme Duval int main()
65*a44af2ecSJérôme Duval {
66*a44af2ecSJérôme Duval thread_local_test(1);
67*a44af2ecSJérôme Duval }
68