-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy paththreads_test.nelua
56 lines (47 loc) · 1.28 KB
/
threads_test.nelua
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
## pragmas.nogc = true
require 'C.threads'
## if ccinfo.has_c11_atomics then
require 'C.stdatomic'
local atomic_counter: integer <atomic> = 0
## end
local counter: integer = 0
local mutex: C.mtx_t
local function thread_safe_print(...: varargs)
assert(C.mtx_lock(&mutex) == C.thrd_success)
print(...)
assert(C.mtx_unlock(&mutex) == C.thrd_success)
end
local function add_thread(arg: pointer): cint
local tid: isize = (@isize)(arg)
thread_safe_print('started thread', tid)
for i=1,1000 do
assert(C.mtx_lock(&mutex) == C.thrd_success)
counter = counter + 1
assert(C.mtx_unlock(&mutex) == C.thrd_success)
## if ccinfo.has_c11_atomics then
C.atomic_fetch_add(&atomic_counter, 1)
## end
end
return tid
end
-- Initialize mutex.
assert(C.mtx_init(&mutex, C.mtx_plain) == C.thrd_success)
-- Create threads.
local thrds: [10]C.thrd_t
for i:isize=0,<10 do
assert(C.thrd_create(&thrds[i], add_thread, (@pointer)(i)) == C.thrd_success)
end
-- Wait threads.
for i=0,<10 do
local res: cint
assert(C.thrd_join(&thrds[i], &res) == C.thrd_success)
assert(res == i)
thread_safe_print('joined thread', i)
end
-- Destroy mutex.
C.mtx_destroy(&mutex)
print('counter', counter)
assert(counter == 10000)
## if ccinfo.has_c11_atomics then
assert(atomic_counter == 10000)
## end