-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathpthread_self.c
105 lines (97 loc) · 2.44 KB
/
pthread_self.c
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* Spawn N threads that print their TID with pthread_self and other
* ID-like information for multiple threads.
*
* https://github.com/cirosantilli/linux-kernel-module-cheat#pthreads
*
* Sample usage:
*
* ....
* ./pthread_tid.out 4
* ....
*
* Sample output:
*
* ....
* 0 tid: 139852943714048
* tid, getpid(), pthread_self() = 0, 13709, 139852943714048
* tid, getpid(), pthread_self() = 1, 13709, 139852935321344
* 1 tid: 139852935321344
* 2 tid: 139852926928640
* tid, getpid(), pthread_self() = 2, 13709, 139852926928640
* 3 tid: 139852918535936
* tid, getpid(), pthread_self() = 3, 13709, 139852918535936
* ....
*
* Note how the PID is the same for all threads.
*/
#define _XOPEN_SOURCE 700
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
void* main_thread(void *arg) {
int argument;
argument = *((int*)arg);
printf(
"tid, getpid(), pthread_self() = "
"%d, %ju, %ju\n",
argument,
(uintmax_t)getpid(),
(uintmax_t)pthread_self()
);
return NULL;
}
int main(int argc, char**argv) {
pthread_t *threads;
unsigned int nthreads, i, *thread_args;
int rc;
/* CLI arguments. */
if (argc > 1) {
nthreads = strtoll(argv[1], NULL, 0);
} else {
nthreads = 1;
}
threads = malloc(nthreads * sizeof(*threads));
thread_args = malloc(nthreads * sizeof(*thread_args));
/* main thread for comparison. */
printf(
"tid, getpid(), pthread_self() = "
"main, %ju, %ju\n",
(uintmax_t)getpid(),
(uintmax_t)pthread_self()
);
/* Create all threads */
for (i = 0; i < nthreads; ++i) {
thread_args[i] = i;
rc = pthread_create(
&threads[i],
NULL,
main_thread,
(void*)&thread_args[i]
);
if (rc != 0) {
errno = rc;
perror("pthread_create");
exit(EXIT_FAILURE);
}
assert(rc == 0);
printf("%d tid: %ju\n", i, (uintmax_t)threads[i]);
}
/* Wait for all threads to complete */
for (i = 0; i < nthreads; ++i) {
rc = pthread_join(threads[i], NULL);
if (rc != 0) {
printf("%s\n", strerror(rc));
exit(EXIT_FAILURE);
}
}
/* Cleanup. */
free(thread_args);
free(threads);
return EXIT_SUCCESS;
}