forked from emscripten-core/emscripten
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_pthread_kill.cpp
More file actions
84 lines (70 loc) · 2.08 KB
/
test_pthread_kill.cpp
File metadata and controls
84 lines (70 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright 2015 The Emscripten Authors. All rights reserved.
// Emscripten is available under two separate licenses, the MIT license and the
// University of Illinois/NCSA Open Source License. Both these licenses can be
// found in the LICENSE file.
#include <pthread.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <emscripten.h>
#include <emscripten/threading.h>
volatile int sharedVar = 0;
static void *thread_start(void *arg)
{
// As long as this thread is running, keep the shared variable latched to nonzero value.
for(;;)
{
++sharedVar;
emscripten_atomic_store_u32((void*)&sharedVar, sharedVar+1);
}
pthread_exit(0);
}
pthread_t thr;
void BusySleep(double msecs)
{
double t0 = emscripten_get_now();
while(emscripten_get_now() < t0 + msecs);
}
int main()
{
if (!emscripten_has_threading_support())
{
#ifdef REPORT_RESULT
REPORT_RESULT(0);
#endif
printf("Skipped: Threading is not supported.\n");
return 0;
}
sharedVar = 0;
int s = pthread_create(&thr, NULL, thread_start, 0);
assert(s == 0);
// Wait until thread kicks in and sets the shared variable.
while(sharedVar == 0)
BusySleep(10);
s = pthread_kill(thr, SIGKILL);
assert(s == 0);
// Wait until we see the shared variable stop incrementing. (This is a bit heuristic and hacky)
for(;;)
{
int val = emscripten_atomic_load_u32((void*)&sharedVar);
BusySleep(100);
int val2 = emscripten_atomic_load_u32((void*)&sharedVar);
if (val == val2) break;
}
// Reset to 0.
sharedVar = 0;
emscripten_atomic_store_u32((void*)&sharedVar, 0);
// Wait for a long time, if the thread is still running, it should progress and set sharedVar by this time.
BusySleep(3000);
// Finally test that the thread is not doing any work and it is dead.
assert(sharedVar == 0);
assert(emscripten_atomic_load_u32((void*)&sharedVar) == 0);
EM_ASM(out('Main: Done. Successfully killed thread. sharedVar: '+$0+'.'), sharedVar);
#ifdef REPORT_RESULT
REPORT_RESULT(sharedVar);
#endif
}