]> git.saurik.com Git - apple/libpthread.git/blob - tests/pthread_threadid_np.c
libpthread-454.100.8.tar.gz
[apple/libpthread.git] / tests / pthread_threadid_np.c
1 #include <pthread.h>
2 #include <pthread/private.h>
3 #include <dispatch/dispatch.h>
4 #include <sys/wait.h>
5 #include <stdlib.h>
6
7 #include "darwintest_defaults.h"
8
9 extern __uint64_t __thread_selfid( void );
10
11 static void *do_test(void * arg)
12 {
13 uint64_t threadid = __thread_selfid();
14 T_ASSERT_NE(threadid, (uint64_t)0, "__thread_selfid()");
15
16 uint64_t pth_threadid = 0;
17 T_ASSERT_POSIX_ZERO(pthread_threadid_np(NULL, &pth_threadid), NULL);
18 T_ASSERT_POSIX_ZERO(pthread_threadid_np(pthread_self(), &pth_threadid), NULL);
19 T_EXPECT_EQ(threadid, pth_threadid, "pthread_threadid_np()");
20
21 pth_threadid = _pthread_threadid_self_np_direct();
22 T_EXPECT_EQ(threadid, pth_threadid, "pthread_threadid_np_direct()");
23
24 if (arg) {
25 *(uint64_t *)arg = pth_threadid;
26 }
27 return NULL;
28 }
29
30 T_DECL(pthread_threadid_np, "pthread_threadid_np",
31 T_META_ALL_VALID_ARCHS(YES))
32 {
33 T_LOG("Main Thread");
34 do_test(NULL);
35
36 T_LOG("Pthread");
37 for (int i = 0; i < 100; i++) {
38 uint64_t tid1 = 0, tid2 = 0;
39 pthread_t pth;
40 T_ASSERT_POSIX_ZERO(pthread_create(&pth, NULL, do_test, &tid1), NULL);
41 T_EXPECT_POSIX_ZERO(pthread_threadid_np(pth, &tid2), NULL);
42 T_ASSERT_POSIX_ZERO(pthread_join(pth, NULL), NULL);
43 T_EXPECT_EQ(tid1, tid2, "parent and child agree");
44 }
45
46 T_LOG("Workqueue Thread");
47 dispatch_queue_t dq = dispatch_queue_create("myqueue", NULL);
48 dispatch_async(dq, ^{ do_test(NULL); });
49 dispatch_sync(dq, ^{});
50
51 T_LOG("Workqueue Thread Reuse");
52 dispatch_async(dq, ^{ do_test(NULL); });
53 dispatch_sync(dq, ^{});
54 }
55
56 T_DECL(pthread_threadid_fork, "pthread_threadid_np post-fork test")
57 {
58 uint64_t tid = __thread_selfid();
59 T_ASSERT_NE(tid, (uint64_t)0, "__thread_selfid()");
60
61 uint64_t ptid = 0;
62 T_ASSERT_POSIX_ZERO(pthread_threadid_np(NULL, &ptid), NULL);
63 T_ASSERT_EQ(ptid, tid, NULL);
64
65 pid_t pid = fork();
66 if (pid == 0) {
67 // child
68 uint64_t ntid = __thread_selfid();
69 if (ntid == tid) {
70 T_LOG("FAIL: forked child tid is equal to parent tid");
71 exit(1);
72 }
73
74 uint64_t nptid = 0;
75 if (pthread_threadid_np(NULL, &nptid) != 0) {
76 T_LOG("FAIL: pthread_threadid_np: %d", errno);
77 exit(1);
78 }
79
80 if (nptid != ntid) {
81 T_LOG("FAIL: pthread_threadid_np == tid (expected: %lld == %lld)",
82 nptid, ntid);
83 exit(1);
84 }
85 exit(0);
86 } else {
87 int status;
88 T_ASSERT_EQ(waitpid(pid, &status, 0), pid, NULL);
89 int exitstatus = WEXITSTATUS(status);
90 T_ASSERT_EQ(exitstatus, 0, NULL);
91 }
92 }