File: test_c_thread_register_cstubs.c

package info (click to toggle)
ocaml 5.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 44,372 kB
  • sloc: ml: 370,196; ansic: 52,820; sh: 27,419; asm: 5,462; makefile: 3,684; python: 974; awk: 278; javascript: 273; perl: 59; fortran: 21; cs: 9
file content (55 lines) | stat: -rw-r--r-- 1,178 bytes parent folder | download | duplicates (2)
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
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#define THREAD_FUNCTION DWORD WINAPI
#else
#include <pthread.h>
#define THREAD_FUNCTION void *
#endif
#include <caml/mlvalues.h>
#include <caml/gc.h>
#include <caml/memory.h>
#include <caml/callback.h>
#include <caml/threads.h>

void *create_root(value v)
{
  value *root = malloc(sizeof(value));
  *root = v;
  caml_register_generational_global_root(root);
  return (void*)root;
}

value consume_root(void *r)
{
  value *root = (value *)r;
  value v = *root;
  caml_remove_generational_global_root(root);
  free(root);
  return v;
}

THREAD_FUNCTION thread_func(void *root)
{
  caml_c_thread_register();
  caml_acquire_runtime_system();
  caml_callback(consume_root(root), Val_unit);
  caml_release_runtime_system();
  caml_c_thread_unregister();
  return 0;
}

value spawn_thread(value clos)
{
  void *root = create_root(clos);
#if _WIN32
  CloseHandle(CreateThread(NULL, 0, &thread_func, root, 0, NULL));
#else
  pthread_t thr;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  pthread_create(&thr, &attr, thread_func, root);
#endif
  return Val_unit;
}