Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/test/core/pthread/create.c
4154 views
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 <stdatomic.h>
7
#include <stdio.h>
8
#include <stdlib.h>
9
#include <pthread.h>
10
#include <assert.h>
11
#include <emscripten.h>
12
13
14
#define NUM_THREADS 2
15
#define TOTAL 100
16
17
static _Atomic int sum;
18
19
void *ThreadMain(void *arg) {
20
for (int i = 0; i < TOTAL; i++) {
21
// wait for a change, so we see interleaved processing.
22
int last = ++sum;
23
while (sum == last) {}
24
}
25
pthread_exit((void*)TOTAL);
26
}
27
28
pthread_t thread[NUM_THREADS];
29
30
void CreateThread(long i) {
31
int rc = pthread_create(&thread[i], NULL, ThreadMain, (void*)i);
32
assert(rc == 0);
33
}
34
35
void main_iter() {
36
static int main_adds = 0;
37
int worker_adds = sum++ - main_adds++;
38
printf("main iter %d : %d\n", main_adds, worker_adds);
39
if (worker_adds == NUM_THREADS * TOTAL) {
40
printf("done!\n");
41
#ifndef ALLOW_SYNC
42
emscripten_cancel_main_loop();
43
#endif
44
exit(0);
45
}
46
}
47
48
int main() {
49
// Create initial threads.
50
for (long i = 0; i < NUM_THREADS; ++i) {
51
CreateThread(i);
52
}
53
54
// if we don't allow sync pthread creation, the event loop must be reached for
55
// the worker to start up.
56
#ifndef ALLOW_SYNC
57
emscripten_set_main_loop(main_iter, 0, 0);
58
#else
59
while (1) {
60
main_iter();
61
}
62
#endif
63
return 0;
64
}
65
66