DataReelDataReelC++ Transition Guide

Examples › Thread Examples

threads_condition

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

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

Modern equivalent of the condition variable example. gxMutex and gxCondition become std::mutex and std::condition_variable. The wait takes the predicate, so the "while(is_locked) ConditionWait()" loop is one call and spurious wake ups are handled. std::unique_lock unlocks on every return path.

The legacy program passes &i (the loop counter) to every thread, so a thread can print a number another thread also prints. std::thread copies its arguments, so each thread gets its own number.

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.
gxCondition, ConditionWait()/ConditionSignal()std::condition_variable wait(lock, predicate) / notify_one()C++11The predicate form handles spurious wake ups.

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_threads/condition/testprog.cpp 103 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"

#ifdef __MSVC_DEBUG__
#include "leaktest.h"
#endif

// For safe condition variable usage, must use a Boolean predicate and 
// a mutex with the condition.
int is_locked = 0;
gxCondition cond;
gxMutex mutex;

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());

  // Serialize access to the shared resource.
  mutex.MutexLock();
  
  int num_try = 0;
  while(is_locked != 0) {
    if(++num_try < 255) {
      cout << "Thread " << num << " execution blocked..." << "\n" << flush;
      cond.ConditionWait(&mutex);
    }
    else {
      cout << "Thread " << num << " could not wait for condition" 
	   << "\n" << flush;
      mutex.MutexUnlock();
      return 0;
    }
  }

  // Tell other threads to wait until shared resource is available
  is_locked = 1;

  // ********** Enter Critical Section ******************* //
  cout << "Thread " << num << " accesing shared resource" << "\n" << flush;
  // ...
  // ...
  // ...
  cout << "Thread " << num << " releasing shared resource" << "\n" << flush;
  // ********** Leave Critical Section ******************* //

  // Tell other threads shared resource is available
  is_locked = 0;

  // Wake up the next thread waiting on this condition
  cond.ConditionSignal();
  mutex.MutexUnlock();
  
  return 0;
}

int main(int argc, char **argv)
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  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++) thread[i] = t.CreateThread((void *)&i); 

  // 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) delete thread[i];

  cout << "Exiting program" << "\n" << flush;
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //


  

Modern C++ (C++11)

examples_modern/threads/condition/modern.cpp 46 lines
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

namespace {
bool is_locked = false;          // Boolean predicate
std::condition_variable cond;    // gxCondition
std::mutex mtx;                  // gxMutex
}

void worker(int num)
{
  std::unique_lock<std::mutex> lock(mtx);   // MutexLock()
  if(is_locked) std::cout << "Thread " << num << " execution blocked...\n";
  cond.wait(lock, [] { return !is_locked; }); // ConditionWait() loop

  is_locked = true;
  // ********** Enter Critical Section ******************* //
  std::cout << "Thread " << num << " accessing shared resource\n";
  std::cout << "Thread " << num << " releasing shared resource\n";
  // ********** Leave Critical Section ******************* //
  is_locked = false;

  cond.notify_one();                        // ConditionSignal()
}                                           // MutexUnlock() by ~unique_lock

int main()
{
  const int NUM_THREADS = 5;
  std::vector<std::thread> threads;

  std::cout << "Create " << NUM_THREADS << " threads\n";
  for(int i = 0; i < NUM_THREADS; i++) threads.emplace_back(worker, i);

  std::cout << "Waiting for all threads before exiting\n";
  for(auto &t : threads) t.join();          // No delete needed

  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_condition
./build-modern/threads_condition
# or without CMake:
g++ -std=c++11 -pthread -o threads_condition examples_modern/threads/condition/modern.cpp

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

Create 5 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
Thread 3 accessing shared resource
Thread 3 releasing shared resource
Waiting for all threads before exiting
Thread 4 accessing shared resource
Thread 4 releasing shared resource
Exiting program