1- #include " thread.h"
21#include < iostream>
32#include < thread>
43#include < chrono>
54#include < atomic>
65#include < string>
76#include < random>
8- #include < pthread.h >
7+ #include < mutex >
98
109// Thread-safe counter for thread IDs
1110static std::atomic<int > g_tid{0 };
1211
13- // Generate fibonacci numbers recursively
12+ // Mutex for thread-safe console output
13+ static std::mutex cout_mutex;
14+
15+ // Generate fibonacci numbers recursively (memoization would be better)
1416static int fib (int n) {
15- switch (n) {
16- case 0 : return 1 ;
17- case 1 : return 1 ;
18- default : return fib (n - 1 ) + fib (n - 2 );
19- }
17+ if (n <= 1 ) return 1 ;
18+ return fib (n - 1 ) + fib (n - 2 );
2019}
2120
22- // Set thread name (platform-specific) with Linux truncation
21+ // Cross-platform thread naming (C++20 would use std::jthread)
2322static void set_thread_name (const std::string& name) {
24- #if defined(__APPLE__)
25- pthread_setname_np (name. c_str ());
26- # elif defined(__linux__)
27- std::string n = name. substr ( 0 , 15 ); // limit ≤15 chars plus null (Linux limit) :contentReference[oaicite:0]{index=0}
28- pthread_setname_np ( pthread_self (), n. c_str ());
23+ #ifdef __cpp_lib_jthread
24+ // Future C++20 implementation
25+ // std::jthread::set_name(name);
26+ # else
27+ // Current placeholder
2928#endif
3029}
3130
32- // Thread-local RNG for good random delays
31+ // Thread-local RNG for random delays
3332static thread_local std::mt19937_64 rng{std::random_device{}()};
3433
3534// Uniform integer generator
@@ -38,17 +37,25 @@ static int intRand(int min, int max) {
3837}
3938
4039void thread_proc () {
41- int tid = g_tid.fetch_add (1 , std::memory_order_relaxed);
42- std::string thread_name = " Thread " + std::to_string (tid);
40+ const int tid = g_tid.fetch_add (1 , std::memory_order_relaxed);
41+ const std::string thread_name = " Thread " + std::to_string (tid);
4342 set_thread_name (thread_name);
4443
45- auto delay = std::chrono::nanoseconds (500000000 + intRand (0 , 500000000 ));
44+ const auto delay = std::chrono::nanoseconds (500000000 + intRand (0 , 500000000 ));
4645
4746 std::this_thread::sleep_for (delay);
47+
4848 for (int i = 0 ; i <= 30 ; ++i) {
49- std::cout << thread_name << " : fib(" << i << " ) = " << fib (i) << " \n " ;
49+ {
50+ std::lock_guard<std::mutex> lock (cout_mutex);
51+ std::cout << thread_name << " : fib(" << i << " ) = " << fib (i) << std::endl;
52+ }
5053 std::this_thread::sleep_for (delay);
5154 }
5255
53- std::cout << thread_name << " exited!\n " ;
56+ {
57+ std::lock_guard<std::mutex> lock (cout_mutex);
58+ std::cout << thread_name << " exited!" << std::endl;
59+ }
5460}
61+
0 commit comments