From 7aaa1b057eabcd9b154de9c85df6c8b880283384 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Wed, 23 Mar 2022 11:27:08 +0200 Subject: [PATCH] sync: add `pub sync.thread_id() u64 {` API --- vlib/sync/sync_darwin.c.v | 1 + vlib/sync/sync_default.c.v | 1 + vlib/sync/sync_windows.c.v | 1 + vlib/sync/thread.c.v | 9 +++++++++ vlib/sync/thread_test.v | 22 ++++++++++++++++++++++ 5 files changed, 34 insertions(+) create mode 100644 vlib/sync/thread.c.v create mode 100644 vlib/sync/thread_test.v diff --git a/vlib/sync/sync_darwin.c.v b/vlib/sync/sync_darwin.c.v index b46ec05903..96106d3d8e 100644 --- a/vlib/sync/sync_darwin.c.v +++ b/vlib/sync/sync_darwin.c.v @@ -10,6 +10,7 @@ import time #include [trusted] +fn C.pthread_self() usize fn C.pthread_mutex_init(voidptr, voidptr) int fn C.pthread_mutex_lock(voidptr) int fn C.pthread_mutex_unlock(voidptr) int diff --git a/vlib/sync/sync_default.c.v b/vlib/sync/sync_default.c.v index 5a1680b209..72f6f39183 100644 --- a/vlib/sync/sync_default.c.v +++ b/vlib/sync/sync_default.c.v @@ -14,6 +14,7 @@ $if !android { #include [trusted] +fn C.pthread_self() usize fn C.pthread_mutex_init(voidptr, voidptr) int fn C.pthread_mutex_lock(voidptr) int fn C.pthread_mutex_unlock(voidptr) int diff --git a/vlib/sync/sync_windows.c.v b/vlib/sync/sync_windows.c.v index 7826edf4cd..de4c216d62 100644 --- a/vlib/sync/sync_windows.c.v +++ b/vlib/sync/sync_windows.c.v @@ -8,6 +8,7 @@ import time #include #include +fn C.GetCurrentThreadId() u32 fn C.GetSystemTimeAsFileTime(lpSystemTimeAsFileTime &C._FILETIME) fn C.InitializeConditionVariable(voidptr) fn C.WakeConditionVariable(voidptr) diff --git a/vlib/sync/thread.c.v b/vlib/sync/thread.c.v new file mode 100644 index 0000000000..8ea1739914 --- /dev/null +++ b/vlib/sync/thread.c.v @@ -0,0 +1,9 @@ +module sync + +pub fn thread_id() u64 { + $if windows { + return u64(C.GetCurrentThreadId()) + } $else { + return u64(C.pthread_self()) + } +} diff --git a/vlib/sync/thread_test.v b/vlib/sync/thread_test.v new file mode 100644 index 0000000000..797d7e9ea6 --- /dev/null +++ b/vlib/sync/thread_test.v @@ -0,0 +1,22 @@ +import sync + +fn simple_thread() u64 { + tid := sync.thread_id() + eprintln('simple_thread thread_id: $tid.hex()') + return tid +} + +fn test_sync_thread_id() { + mtid := sync.thread_id() + eprintln('main thread_id: $sync.thread_id().hex()') + x := go simple_thread() + y := go simple_thread() + xtid := x.wait() + ytid := y.wait() + eprintln('main thread_id: $sync.thread_id().hex()') + dump(xtid.hex()) + dump(ytid.hex()) + assert mtid != xtid + assert mtid != ytid + assert xtid != ytid +}