1 // Copyright 2015 The Emscripten Authors.  All rights reserved.
2 // Emscripten is available under two separate licenses, the MIT license and the
3 // University of Illinois/NCSA Open Source License.  Both these licenses can be
4 // found in the LICENSE file.
5 
6 #include <pthread.h>
7 #include <errno.h>
8 #include <emscripten.h>
9 #include <emscripten/threading.h>
10 
11 // Toggle to use two different methods for updating shared data (C++03 volatile vs explicit atomic ops).
12 // Note that using a volatile variable explicitly depends on x86 strong memory model semantics.
13 //#define USE_C_VOLATILE
14 
15 volatile int sharedVar = 0;
16 
thread_start(void * arg)17 static void *thread_start(void *arg) // thread: just flip the shared flag and quit.
18 {
19 #ifdef USE_C_VOLATILE
20   sharedVar = 1;
21 #else
22   emscripten_atomic_store_u32((void*)&sharedVar, 1);
23 #endif
24   pthread_exit(0);
25 }
26 
main()27 int main()
28 {
29   int result;
30   if (!emscripten_has_threading_support())
31   {
32 #ifdef REPORT_RESULT
33     REPORT_RESULT(1);
34 #endif
35     printf("Skipped: Threading is not supported.\n");
36     return 0;
37   }
38 
39   pthread_t thr;
40   int rc = pthread_create(&thr, NULL, thread_start, (void*)0);
41   if (rc != 0)
42   {
43 #ifdef REPORT_RESULT
44     int result = (rc != EAGAIN);
45     REPORT_RESULT(result);
46     return 0;
47 #endif
48   }
49 
50 #ifdef USE_C_VOLATILE
51   while(sharedVar == 0)
52     ;
53 #else
54   while(emscripten_atomic_load_u32((void*)&sharedVar) == 0) {}
55 #endif
56 
57 #ifdef REPORT_RESULT
58   REPORT_RESULT(sharedVar);
59 #endif
60 }
61