1 // Copyright 2016 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <inttypes.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <threads.h>
9 #include <time.h>
10 
11 #include <zircon/syscalls.h>
12 #include <stdatomic.h>
13 
14 static atomic_uint_fast64_t count = ATOMIC_VAR_INIT(0);
15 
thread_func(void * arg)16 static int thread_func(void* arg) {
17     uint64_t val = atomic_fetch_add(&count, 1);
18     val++;
19     if (val % 1000 == 0) {
20         printf("Created %" PRId64 " threads, time %" PRId64 " us\n", val,
21                zx_clock_get_monotonic() / 1000000);
22     }
23 
24     thrd_t thread;
25     int ret = thrd_create_with_name(&thread, thread_func, NULL, "depth");
26     if (ret == thrd_success) {
27         ret = thrd_join(thread, NULL);
28         if (ret != thrd_success) {
29             printf("Unexpected thread join return: %d\n", ret);
30             return 1;
31         }
32         val = atomic_fetch_sub(&count, 1);
33         val--;
34         if (val % 1000 == 0)
35             printf("Joined %" PRId64 " threads, time %" PRId64 " us\n", val,
36                    zx_clock_get_monotonic() / 1000000);
37     }
38 
39     return 0;
40 }
41 
main(int argc,char ** argv)42 int main(int argc, char** argv) {
43     printf("Running thread depth test...\n");
44 
45     thrd_t thread;
46     int ret = thrd_create_with_name(&thread, thread_func, NULL, "depth");
47     ret = thrd_join(thread, NULL);
48     if (ret != thrd_success) {
49         printf("Unexpected thread join return: %d\n", ret);
50         return 1;
51     }
52 
53     // TODO(phosek): The cast here shouldn't be required.
54     printf("Created %" PRIdFAST64 " threads\n", (uint_fast64_t)atomic_load(&count));
55     return 0;
56 }
57