Examples › Thread Examples
threads_deadlock2
C++11 or laterC++ standard library onlyPortable C++ (tested on Linux)
Legacy: examples_threads/deadlock2/testprog.cpp · Modern: examples_modern/threads/deadlock2/modern.cpp
Modern equivalent of deadlock2, where the application recovers a mutex whose owner died (gxMUTEX_OWNERDEAD_ERROR, MakeConsistent()). Inside one process, RAII locks make an abandoned mutex impossible (see deadlock1). What an application can still do is refuse to wait forever: std::timed_mutex::try_lock_for() gives up after a timeout, and the caller decides what to do. A lock that has to survive a crashed process (a mutex in shared memory) still needs the platform API: a POSIX robust mutex, see deadlock_posix_testing.
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. |
| gxMutex, MutexLock()/MutexUnlock() | std::mutex + std::scoped_lock / std::lock_guard / std::unique_lock | C++11 / C++17 | The lock is released by a destructor on every path, so a return cannot leave it locked. |
| 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/deadlock2/testprog.cpp 114 lines
#include "gxdlcode.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" #include "gxcond.h" #include "gxmutex.h" // Boolean predicate and a mutex int is_locked = 0; gxMutex mutex; int value = 0; class SimpleThread : public gxThread { private: // Base class interface void *ThreadEntryRoutine(gxThread_t *thread); }; void *SimpleThread::ThreadEntryRoutine(gxThread_t *thread) // Thread's entry function { int num = *((int *)thread->GetThreadParm()); int has_mutex = 1; if(mutex.MutexLock() != 0) { cout << gxThreadMutexExceptionMessage(mutex.GetMutex()) << "\n" << flush; if(mutex.GetMutexError() == gxMUTEX_OWNERDEAD_ERROR) { if(mutex.MakeConsistent() != 0) { // This thread now owns this lock cout << gxThreadMutexExceptionMessage(mutex.GetMutex()) << "\n" << flush; if(mutex.MutexUnlock() != 0) { // Unable to make the state consistent cout << gxThreadMutexExceptionMessage(mutex.GetMutex()) << "\n" << flush; } has_mutex = 0; } } else { cout << gxThreadMutexExceptionMessage(mutex.GetMutex()) << "\n" << flush; has_mutex = 0; } } if(!has_mutex) cout << "Lock failed for " << num << "\n"; if(is_locked && !has_mutex) return 0; if(num == 3) return 0; // Simulate a deadlock by exiting before unlocking // Tell other threads to wait until shared resource is available is_locked = 1; if(num == 4 || num == 6) return 0; // Simulate a deadlock by exiting before unlocking // ********** Enter Critical Section ******************* // cout << "Thread " << num << " accesing shared resource" << "\n" << flush; // ... value++; // ... cout << "Thread " << num << " releasing shared resource" << "\n" << flush; // ********** Leave Critical Section ******************* // // Tell other threads shared resource is available is_locked = 0; if(has_mutex) { if(mutex.MutexUnlock() != 0) { cout << gxThreadMutexExceptionMessage(mutex.GetMutex()) << "\n" << flush; } } return 0; } int main(int argc, char **argv) { const int NUM_THREADS = 10; SimpleThread t; gxThread_t *thread[NUM_THREADS]; mutex.DisableAutoFix(); cout << "\nCreate " << 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 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(); if(tcount) { delete tcount; tcount = 0; } delete thread[i]; thread[i] = 0; } cout << "Final value = " << value << "\n\n" << flush; return 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++11)
examples_modern/threads/deadlock2/modern.cpp 50 lines
#include <chrono> #include <iostream> #include <mutex> #include <thread> #include <vector> using namespace std::chrono; namespace { std::timed_mutex mtx; int value = 0; } void worker(int num) { std::unique_lock<std::timed_mutex> lock(mtx, std::defer_lock); if(!lock.try_lock_for(milliseconds(500))) { std::cout << "Lock failed for " << num << " (timed out)\n"; return; } if(num == 3) { // Hold the lock for longer than the others will wait, to show // the timeout path. The lock is still released on return. std::this_thread::sleep_for(milliseconds(800)); return; } std::cout << "Thread " << num << " accessing shared resource\n"; value++; std::cout << "Thread " << num << " releasing shared resource\n"; } int main() { const int NUM_THREADS = 10; std::vector<std::thread> threads; std::cout << "\nCreate " << NUM_THREADS << " threads\n"; for(int i = 0; i < NUM_THREADS; i++) { threads.emplace_back(worker, i); if(i == 3) std::this_thread::sleep_for(milliseconds(50)); } for(auto &t : threads) t.join(); std::cout << "Final value = " << value << "\n\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_deadlock2 ./build-modern/threads_deadlock2 # or without CMake: g++ -std=c++11 -pthread -o threads_deadlock2 examples_modern/threads/deadlock2/modern.cpp
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
Create 10 threads Thread 0 accessing shared resource Thread 0 releasing shared resource Thread 1 accessing shared resource Thread 1 releasing shared resource Thread 2 accessing shared resource Thread 2 releasing shared resource Lock failed for 4 (timed out) Lock failed for 6 (timed out) Lock failed for 7 (timed out) Lock failed for 5 (timed out) Lock failed for 9 (timed out) Lock failed for 8 (timed out) Final value = 3