Finch/tests/new/threads.fch
Nexoniarz d428498efd finch.toml, threads and atomics, finch fmt, C++ files, struct #defines, a struct variable given for its ptr
- finch.toml: name, entry, paths, include, links, libdirs, cflags, ldflags, and [target.windows] etc.;
  finch run / build / test with no file use its entry
- import thread: spawn, join, mutex, cpus; atomic_add/sub/load/store/swap/cas built in
- finch fmt [--check]: indentation by { }, trailing spaces, empty lines; also as LSP formatting
- link "x.cpp" (or in finch.toml): built with the C++ compiler, which then links (FINCH_CXX)
- #define RAYWHITE (Color){ 245, 245, 245, 255 } imports as a Color
- push(body) where push takes ptr[Body]: the same as push(addr(body))
- --target android (NDK clang from ANDROID_NDK_HOME, -llog)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016GzNP6r8dg6WDxUVZy8wjL
2026-10-29 11:17:10 +01:00

55 lines
1.1 KiB
Text

import thread
struct Shared {
[]int seen
}
struct Job {
ptr[int] counter
int adds
ptr[thread.Mutex] lock
ptr[Shared] common
int id
}
fn work(ptr arg) {
ptr[Job] job = arg
for i in 0..job.adds {
atomic_add(job.counter, 1)
}
job.lock.lock()
job.common.seen.push(job.id)
job.lock.unlock()
}
fn main() {
count := 0
m := thread.mutex()
defer m.close()
both := Shared()
[]Job jobs
for i in 0..4 {
jobs.push(Job(counter: addr(count), adds: 100000, lock: addr(m), common: addr(both), id: i))
}
[]thread.Thread ts
for i in 0..4 {
ts.push(thread.spawn(addr(work), addr(jobs[i])) or {
print("can't start")
exit(1)
})
}
for i in 0..4 {
ts[i].join()
}
print(atomic_load(addr(count)))
print(both.seen.len)
print(thread.cpus() > 0)
u32 flags = 5
print(atomic_swap(addr(flags), 9))
print(atomic_cas(addr(flags), 9, 1))
print(atomic_cas(addr(flags), 9, 2))
atomic_store(addr(flags), 7)
print(atomic_sub(addr(flags), 2))
print(flags)
}