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