1 // Copyright 2019 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 <sys/types.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <assert.h>
11 #include <emscripten.h>
12 #include <emscripten/threading.h>
13 
thread_start(void * arg)14 static void *thread_start(void *arg)
15 {
16   char* buffer = (char*)arg;
17   assert(buffer);
18   assert(*buffer == 42);
19   EM_ASM({ assert(HEAP8[$0] === 42, "readable from JS in worker") }, buffer);
20   pthread_exit((void*)43);
21 }
22 
test()23 char* test() {
24   // allocate more memory than we currently have, forcing a growth
25   char* buffer = (char*)malloc(64 * 1024 * 1024);
26   assert(buffer);
27   *buffer = 42;
28   return buffer;
29 }
30 
main()31 int main()
32 {
33   printf("prep\n");
34   if (!emscripten_has_threading_support())
35   {
36 #ifdef REPORT_RESULT
37     REPORT_RESULT(6765);
38 #endif
39     printf("Skipped: Threading is not supported.\n");
40     return 0;
41   }
42 
43   printf("start main\n");
44   EM_ASM({ assert(HEAP8.length === 32 * 1024 * 1024, "start at 32MB") });
45   char* buffer = test();
46   assert(*buffer == 42); // should see the value the code wrote
47   EM_ASM({ assert(HEAP8[$0] === 42, "readable from JS") }, buffer);
48   EM_ASM({ assert(HEAP8.length > 64 * 1024 * 1024, "end with >64MB") });
49 
50   printf("start thread\n");
51   pthread_t thr;
52   int s = pthread_create(&thr, NULL, thread_start, (void*)buffer);
53   assert(s == 0);
54   printf("join\n");
55   void* result = NULL;
56   s = pthread_join(thr, &result);
57   assert(result == (void*)43);
58 
59   printf("finish\n");
60 
61 #ifdef REPORT_RESULT
62   REPORT_RESULT(1);
63 #endif
64 }
65 
66