
Wait for Conditions with pthread_cond_wait
Make a C thread sleep until another signals that work is ready with pthread_cond_wait, pthread_cond_signal and a predicate loop on Linux with glibc 2.41.
Tag
7 posts

Make a C thread sleep until another signals that work is ready with pthread_cond_wait, pthread_cond_signal and a predicate loop on Linux with glibc 2.41.

Guard a shared linked-list stack in C with pthread_mutex_lock and pthread_mutex_unlock on glibc 2.41, check return codes, and avoid leaks from missed unlocks.

Name threads with pthread_setname_np so gdb, top -H and /proc show readable names. Covers the 15-character limit, ERANGE, prctl and C++ and Rust.

Pass arguments to a pthread through void pointers and get results back with pthread_join, a result struct or pthread_exit, without dangling pointers.

Start threads with pthread_create, wait for them with pthread_join and check the error codes correctly. Includes a complete C program and the mistakes to avoid.

One guide to locking in C, C++ and Rust: mutexes, deadlock, condition variables, semaphores, barriers, rwlocks, spinlocks, futexes and debugging.

Learn threads from first principles in C with pthreads, C++ with std::thread and jthread, and Rust: create, join, share data, stop, name and debug them.