8 #include <darwintest.h>
11 pthread_mutex_t mutex
;
16 static void *test_thread(void *ptr
) {
19 struct context
*context
= ptr
;
28 str
= "pthread_mutex_lock";
29 res
= pthread_mutex_lock(&context
->mutex
);
31 str
= "pthread_mutex_trylock";
32 res
= pthread_mutex_trylock(&context
->mutex
);
35 if (try && res
== EBUSY
) {
38 T_ASSERT_POSIX_ZERO(res
, "[%ld] %s", context
->count
, str
);
41 old
= __sync_fetch_and_or(&context
->value
, 1);
43 T_FAIL("[%ld] OR %lx\n", context
->count
, old
);
46 old
= __sync_fetch_and_and(&context
->value
, 0);
48 T_FAIL("[%ld] AND %lx\n", context
->count
, old
);
51 res
= pthread_mutex_unlock(&context
->mutex
);
53 T_ASSERT_POSIX_ZERO(res
, "[%ld] pthread_mutex_lock", context
->count
);
55 } while (__sync_fetch_and_sub(&context
->count
, 1) > 0);
57 T_PASS("thread completed successfully");
62 T_DECL(mutex
, "pthread_mutex",
63 T_META_ALL_VALID_ARCHS(YES
))
65 struct context context
= {
66 .mutex
= PTHREAD_MUTEX_INITIALIZER
,
74 for (i
= 0; i
< threads
; ++i
) {
75 res
= pthread_create(&p
[i
], NULL
, test_thread
, &context
);
76 T_ASSERT_POSIX_ZERO(res
, "pthread_create()");
78 for (i
= 0; i
< threads
; ++i
) {
79 res
= pthread_join(p
[i
], NULL
);
80 T_ASSERT_POSIX_ZERO(res
, "pthread_join()");