Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/test/core/pthread/exceptions.cpp
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 <stdio.h>
7
#include <stdlib.h>
8
#include <pthread.h>
9
#include <assert.h>
10
#include <emscripten.h>
11
12
#include <atomic>
13
14
#define NUM_THREADS 2
15
#define TOTAL 1000
16
#define THREAD_ADDS 750
17
#define MAIN_ADDS 5
18
19
static std::atomic<int> sum;
20
static std::atomic<int> total;
21
22
void *ThreadMain(void *arg) {
23
for (int i = 0; i < TOTAL; i++) {
24
try {
25
// Throw two different types, to make sure we check throwing and landing
26
// pad behavior.
27
if (i & 3) {
28
throw 3.14159f;
29
}
30
throw i;
31
} catch (int x) {
32
total += x;
33
} catch (float f) {
34
// wait for a change, so we see interleaved processing.
35
int last = ++sum;
36
while (sum.load() == last) {}
37
}
38
}
39
pthread_exit((void*)TOTAL);
40
}
41
42
pthread_t thread[NUM_THREADS];
43
44
void CreateThread(int i)
45
{
46
int rc = pthread_create(&thread[i], nullptr, ThreadMain, (void*)(intptr_t)i);
47
assert(rc == 0);
48
}
49
50
void loop() {
51
static int main_adds = 0;
52
int worker_adds = sum++ - main_adds++;
53
printf("main iter %d : %d\n", main_adds, worker_adds);
54
if (worker_adds == NUM_THREADS * THREAD_ADDS &&
55
main_adds >= MAIN_ADDS) {
56
printf("done: %d.\n", total.load());
57
emscripten_cancel_main_loop();
58
exit(0);
59
}
60
}
61
62
int main() {
63
// Create initial threads.
64
for (int i = 0; i < NUM_THREADS; ++i) {
65
printf("make\n");
66
CreateThread(i);
67
}
68
69
emscripten_set_main_loop(loop, 0, 0);
70
return 0;
71
}
72
73