File: test_pthread_join.cpp

package info (click to toggle)
emscripten 3.1.6~dfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 114,112 kB
  • sloc: ansic: 583,052; cpp: 391,943; javascript: 79,361; python: 54,180; sh: 49,997; pascal: 4,658; makefile: 3,426; asm: 2,191; lisp: 1,869; ruby: 488; cs: 142
file content (62 lines) | stat: -rw-r--r-- 1,809 bytes parent folder | download
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
// 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 <emscripten/em_asm.h>

long fib(long n)
{
  if (n <= 0) return 0;
  if (n == 1) return 1;
  return fib(n-1) + fib(n-2);
}

static void *thread_start(void *arg)
{
  long n = (long)arg;
  EM_ASM(out('Thread: Computing fib('+$0+')...'), n);
  long fibn = fib(n);
  EM_ASM(out('Thread: Computation done. fib('+$0+') = '+$1+'.'), n, fibn);
  pthread_exit((void*)fibn);
}

int main()
{
  // Test existence of nanosleep(), https://github.com/emscripten-core/emscripten/issues/4578
  struct timespec ts = { 1, 0 };
  nanosleep(&ts, 0);

  pthread_t thr;

  assert(EM_ASM_INT(return PThread.runningWorkers.length) == 0);
  assert(EM_ASM_INT(return PThread.unusedWorkers.length) == 8); // This test should be run with a prepopulated pool of size 8.

  int n = 20;
  EM_ASM(out('Main: Spawning thread to compute fib('+$0+')...'), n);
  int s = pthread_create(&thr, NULL, thread_start, (void*)n);
  assert(s == 0);
  EM_ASM(out('Main: Waiting for thread to join.'));
  int result = 0;

  assert(EM_ASM_INT(return PThread.runningWorkers.length) == 1);
  assert(EM_ASM_INT(return PThread.unusedWorkers.length) == 7);

  s = pthread_join(thr, (void**)&result);
  assert(s == 0);
  EM_ASM(out('Main: Thread joined with result: '+$0+'.'), result);

  assert(EM_ASM_INT(return PThread.runningWorkers.length) == 0);
  assert(EM_ASM_INT(return PThread.unusedWorkers.length) == 8);

  assert(result == 6765);
  return 0;
}