Examples › Thread Examples
threads_deadlock_posix_testing
C++11 or laterC++ standard library onlyPOSIX (Linux, UNIX)
Legacy: examples_threads/deadlock_posix_testing/testprog.cpp · Modern: examples_modern/threads/deadlock_posix_testing/modern.cpp
Modern equivalent of the POSIX robust mutex test. std::mutex has no robust (owner died) mode, so a robust mutex stays a POSIX object, but it can be wrapped in a small RAII class with the standard Lockable interface (lock, unlock, try_lock). std::lock_guard then works with it, and EOWNERDEAD is handled in one place.
Linux and other POSIX systems only (pthread_mutex_consistent is POSIX 2008; the legacy program used the older _np names).
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| gxThread subclass, CreateThread() | std::thread t(callable, args...) | C++11 | Any function, lambda or functor runs in the thread; arguments are copied with their types (no void *). |
| JoinThread() | t.join(); std::future::get() | C++11 | join() waits; a std::async future's get() also returns the result. |
| DestroyThread(), delete gxThread_t | nothing: the std::thread object owns the thread | C++11 | Join or detach before the object is destroyed, or use std::jthread, which joins itself. |
| robust mutex, MakeConsistent() | std::timed_mutex::try_lock_for(); a POSIX robust mutex wrapped as a Lockable | C++11 / POSIX | Within one process RAII locks make an abandoned mutex impossible. |
| new / delete | automatic objects, containers, std::unique_ptr / std::make_unique | C++11 / C++14 | Ownership is in the type, and release() shows a hand-over. |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_threads/deadlock_posix_testing/testprog.cpp 117 lines
#include "gxdlcode.h" #include <errno.h> #if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library #include <iostream> using namespace std; // Use unqualified names for Standard C++ library #else // Use the old iostream library by default #include <iostream.h> #endif // __USE_ANSI_CPP__ #include "gxthread.h" pthread_mutex_t mutex; class SimpleThread : public gxThread { private: // Base class interface void *ThreadEntryRoutine(gxThread_t *thread); }; int value = 0; void *SimpleThread::ThreadEntryRoutine(gxThread_t *thread) // Thread's entry function { int tid = *((int *)thread->GetThreadParm()); int is_locked = 0; int rv = pthread_mutex_lock(&mutex); if(rv == 0) is_locked = 1; if(rv != 0) { if(rv == EOWNERDEAD) { cout << "ERROR - In thread " << tid << " mutex owner is dead, taking ownership" << "\n" << flush; rv = pthread_mutex_consistent_np(&mutex); // We now own this lock if(rv != 0) { // Cannot recover lock pthread_mutex_unlock(&mutex); // Signal all locks to fail return 0; } is_locked = 1; } } if(!is_locked) { cout << "ERROR - not locked" << "\n" << flush; return 0; } if(tid == 2) return 0; // Simulate a deadlock by exiting thread without unlocking mutex // ********** Enter Critical Section ******************* // cout << "Thread " << tid << " accesing shared resource" << "\n" << flush; // ... value++; // ... cout << "Thread " << tid << " releasing shared resource" << "\n" << flush; // ********** Leave Critical Section ******************* // if(pthread_mutex_unlock(&mutex) != 0) { cout << "ERROR - Error unlocking mutex" << "\n" << flush; } return 0; } void runtest() { const int NUM_THREADS = 5; SimpleThread t; gxThread_t *thread[NUM_THREADS]; cout << "Create " << NUM_THREADS << " threads" << "\n" << flush; int i; for(i = 0; i < NUM_THREADS; i++) { int *tcount = new int; *tcount = i; thread[i] = t.CreateThread((void *)tcount); } // Wait for the all the threads to finish before exiting //cout << "Waiting for all threads before exiting" << "\n" << flush; for(i = 0; i < NUM_THREADS; ++i) t.JoinThread(thread[i]); // Release the memory allocated for each thread for(i = 0; i < NUM_THREADS; ++i) { int *tcount = (int *)thread[i]->GetThreadParm(); delete tcount; tcount = 0; delete thread[i]; thread[i] = 0; } cout << "Final value = " << value << "\n\n" << flush; value = 0; } int main(int argc, char **argv) { pthread_mutexattr_t ma; pthread_mutexattr_init(&ma); // pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_SHARED); pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_PRIVATE); pthread_mutexattr_setrobust_np(&ma, PTHREAD_MUTEX_ROBUST_NP); pthread_mutex_init(&mutex, &ma); int count = 255; int i = 1; while(count--) { cout << "Test number " << i++ << "\n" << flush; runtest(); } cout << "Exiting program" << "\n" << flush; return 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++11)
examples_modern/threads/deadlock_posix_testing/modern.cpp 86 lines
#include <cerrno> #include <iostream> #include <mutex> #include <pthread.h> #include <system_error> #include <thread> #include <vector> class RobustMutex { // Meets the standard Lockable requirements public: RobustMutex() { pthread_mutexattr_t ma; pthread_mutexattr_init(&ma); pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_PRIVATE); pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST); int rv = pthread_mutex_init(&m_, &ma); pthread_mutexattr_destroy(&ma); if(rv != 0) throw std::system_error(rv, std::generic_category()); } ~RobustMutex() { pthread_mutex_destroy(&m_); } RobustMutex(const RobustMutex &) = delete; RobustMutex &operator=(const RobustMutex &) = delete; void lock() { int rv = pthread_mutex_lock(&m_); if(rv == EOWNERDEAD) { owner_died_ = true; rv = pthread_mutex_consistent(&m_); // We now own the lock } if(rv != 0) throw std::system_error(rv, std::generic_category()); } void unlock() { pthread_mutex_unlock(&m_); } bool try_lock() { return pthread_mutex_trylock(&m_) == 0; } // True once after a lock that recovered from a dead owner bool owner_died() { bool d = owner_died_; owner_died_ = false; return d; } private: pthread_mutex_t m_; bool owner_died_ = false; }; namespace { RobustMutex mtx; int value = 0; } void worker(int tid) { if(tid == 2) { // Simulate a thread that ends while it holds the mutex. With a // lock_guard this cannot happen, so it calls lock() by hand. mtx.lock(); return; } std::lock_guard<RobustMutex> lock(mtx); if(mtx.owner_died()) std::cout << "In thread " << tid << " mutex owner is dead, took ownership\n"; std::cout << "Thread " << tid << " accessing shared resource\n"; value++; } int main() { const int NUM_THREADS = 5; for(int test = 1; test <= 3; test++) { std::cout << "Test number " << test << "\n"; std::vector<std::thread> threads; for(int i = 0; i < NUM_THREADS; i++) threads.emplace_back(worker, i); for(auto &t : threads) t.join(); std::cout << "Final value = " << value << "\n\n"; value = 0; } // If thread 2 of the last test was the last to lock, its lock is // still held by a dead thread: lock() recovers it. mtx.lock(); if(mtx.owner_died()) std::cout << "Recovered the lock left by thread 2\n"; mtx.unlock(); std::cout << "Exiting program\n"; return 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Build and run
cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=11 cmake --build build-modern --target threads_deadlock_posix_testing ./build-modern/threads_deadlock_posix_testing # or without CMake: g++ -std=c++11 -pthread -o threads_deadlock_posix_testing examples_modern/threads/deadlock_posix_testing/modern.cpp
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
Test number 1 Thread 0 accessing shared resource Thread 1 accessing shared resource Thread 3 accessing shared resource Thread 4 accessing shared resource Final value = 4 Test number 2 In thread 0 mutex owner is dead, took ownership Thread 0 accessing shared resource Thread 1 accessing shared resource In thread 3 mutex owner is dead, took ownership Thread 3 accessing shared resource Thread 4 accessing shared resource Final value = 4 Test number 3 Thread 0 accessing shared resource Thread 1 accessing shared resource In thread 3 mutex owner is dead, took ownership Thread 3 accessing shared resource Thread 4 accessing shared resource Final value = 4 Exiting program