summaryrefslogtreecommitdiff
path: root/test/example/cpp-threads.cpp
blob: 4a41249e78320aae5c2fb934c90bda059c412052 (plain)
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
// test multiple uses of the threadPool

#include <iostream>
#include <thread>
#include <vector>
 
#include <binaryen-c.h>

int NUM_THREADS = 33;

void worker() {
  BinaryenModuleRef module = BinaryenModuleCreate();

  // Create a function type for  i32 (i32, i32)
  BinaryenType params[2] = { BinaryenTypeInt32(), BinaryenTypeInt32() };
  BinaryenFunctionTypeRef iii = BinaryenAddFunctionType(module, "iii", BinaryenTypeInt32(), params, 2);

  // Get the 0 and 1 arguments, and add them
  BinaryenExpressionRef x = BinaryenGetLocal(module, 0, BinaryenTypeInt32()),
                        y = BinaryenGetLocal(module, 1, BinaryenTypeInt32());
  BinaryenExpressionRef add = BinaryenBinary(module, BinaryenAddInt32(), x, y);
  BinaryenExpressionRef ret = BinaryenReturn(module, add);

  // Create the add function
  // Note: no additional local variables
  // Note: no basic blocks here, we are an AST. The function body is just an expression node.
  BinaryenFunctionRef adder = BinaryenAddFunction(module, "adder", iii, NULL, 0, ret);

  // validate it
  BinaryenModuleValidate(module);

  // optimize it
  BinaryenModuleOptimize(module);
  BinaryenModuleValidate(module);

  // Clean up the module, which owns all the objects we created above
  BinaryenModuleDispose(module);
}

int main() 
{
  std::vector<std::thread> threads;

  std::cout << "create threads...\n";
  for (int i = 0; i < NUM_THREADS; i++) {
    threads.emplace_back(worker);
  }
  std::cout << "threads running in parallel...\n";

  std::cout << "waiting for threads to join...\n";
  for (auto& thread : threads) {
    thread.join();
  }

  std::cout << "all done.\n";

  return 0;
}