DataReelDataReelC++ Transition Guide

Examples › Thread Examples

threads_deadlock1

C++17 or laterC++ standard library onlyPortable C++ (tested on Linux)

Legacy: examples_threads/deadlock1/testprog.cpp · Modern: examples_modern/threads/deadlock1/modern.cpp

Modern equivalent of deadlock1. The legacy program makes threads 3, 4 and 6 return while they hold the mutex, and gxMutex recovers the lock (a POSIX robust mutex). With std::lock_guard or std::scoped_lock the unlock is done by a destructor, so a return (or an exception) in the middle of the critical section cannot leave the mutex locked: the deadlock cannot happen, and no recovery code is needed.

Legacy calls in this program

LegacyModern C++StandardNotes
gxThread subclass, CreateThread()std::thread t(callable, args...)C++11Any function, lambda or functor runs in the thread; arguments are copied with their types (no void *).
JoinThread()t.join(); std::future::get()C++11join() waits; a std::async future's get() also returns the result.
DestroyThread(), delete gxThread_tnothing: the std::thread object owns the threadC++11Join 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_lockC++11 / C++17The lock is released by a destructor on every path, so a return cannot leave it locked.
new / deleteautomatic objects, containers, std::unique_ptr / std::make_uniqueC++11 / C++14Ownership is in the type, and release() shows a hand-over.

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_threads/deadlock1/testprog.cpp 105 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;
    has_mutex = 0;
  }

  if(!has_mutex) cout << "Lock failed for " << num << "\n";

  // NOTE: This is application dependant, for more complex operations we need to add
  // NOTE: a condition here, fail, or exit the program. In this example we can continue
  // NOTE: if no other thread is accessing the critical data and we cannot get a mutex
  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];

  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++17)

examples_modern/threads/deadlock1/modern.cpp 43 lines
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

namespace {
std::mutex mtx;
int value = 0;
}

void worker(int num)
{
  std::scoped_lock lock(mtx);   // C++17; std::lock_guard in C++11

  // The legacy "simulate a deadlock by exiting before unlocking":
  // here the return releases the lock.
  if(num == 3 || num == 4 || num == 6) {
    std::cout << "Thread " << num << " returned early, lock released\n";
    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";
  // The thread number is copied into the thread: no new int / delete
  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";
  return value == NUM_THREADS - 3 ? 0 : 1;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target threads_deadlock1
./build-modern/threads_deadlock1
# or without CMake:
g++ -std=c++17 -pthread -o threads_deadlock1 examples_modern/threads/deadlock1/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 3 returned early, lock released
Thread 2 accessing shared resource
Thread 2 releasing shared resource
Thread 4 returned early, lock released
Thread 5 accessing shared resource
Thread 5 releasing shared resource
Thread 6 returned early, lock released
Thread 7 accessing shared resource
Thread 7 releasing shared resource
Thread 8 accessing shared resource
Thread 8 releasing shared resource
Thread 9 accessing shared resource
Thread 9 releasing shared resource
Final value = 7