ref: 1c557dc95cee8934e942cab92e3f1c85fbf0a9c9
parent: 68db3e9d5d605e581337692be1e7ba02739af9af
author: grobe0ba <grobe0ba@tcp80.org>
date: Sat Dec 31 10:02:37 CST 2022
add mutex to prevent concurrent writes to console in test
--- a/pthread.ha
+++ b/pthread.ha
@@ -113,12 +113,16 @@
type thread_info = struct {
thread_id: pthread_t,
thread_num: int,
+ thread_data: nullable *void,
};
fn thread_start(arg: *void) nullable *void = {
let tinfo: *thread_info = (arg: *thread_info);
+ let wrmtx: *mutex_t = (tinfo.thread_data: *mutex_t);
+ mutex_lock(wrmtx);
fmt::printf("Thread {}\n", tinfo.thread_num)!;
+ mutex_unlock(wrmtx);
return null;
};
@@ -132,9 +136,15 @@
fmt::fatal("pthread::attr_init");
};
- let tinfo: [4]thread_info = [thread_info { thread_id = null, thread_num = 0 }...];
+ let wrmtx: mutex_t = null;
+ let mtxattr: mutexattr_t = null;
+ mutexattr_init(&mtxattr);
+ mutex_init(&wrmtx, &mtxattr);
+
+ let tinfo: [4]thread_info = [thread_info { thread_id = null, thread_num = 0, thread_data = &wrmtx }...];
+
for (let i = 0; i < num_threads; i += 1) {
tinfo[i].thread_num = i + 1;
@@ -152,7 +162,9 @@
fmt::fatal("pthread::join");
};
- fmt::printf("Joined with thread {}...", tinfo[i].thread_num)!;
+ mutex_lock(&wrmtx);
+ fmt::printf("Joined with thread {}...\n", tinfo[i].thread_num)!;
+ mutex_unlock(&wrmtx);
};
};