DataReelDataReelC++ Transition Guide

Examples › Thread Examples

threads_mutex

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

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

Modern equivalent of the mutex example. gxMutex becomes std::mutex. MutexLock()/MutexUnlock() pairs become std::scoped_lock (C++17) or std::lock_guard (C++11), which unlock in their destructor. main() holds the lock in a std::unique_lock so it can unlock it before the end of the scope.

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.
sSleep(), mSleep(), uSleep(), nSleep()std::this_thread::sleep_for(1s), (500ms), (100us), (100ns)C++11 (literals C++14)The unit is part of the std::chrono duration type.
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.

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_threads/mutex/testprog.cpp 115 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 "gxmutex.h"

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

// Constants
const int NUMTHREADS = 3;

// Mutex that will be shared by threads within this process
gxMutex mutex;

// Shared data
int sharedData1 = 0;
int sharedData2 = 0;

class SimpleThread : public gxThread
{
public:
  SimpleThread() { }
  ~SimpleThread();
  
public:
  void Begin();
  void End();
  
private: // Base class interface
  void *ThreadEntryRoutine(gxThread_t *thread);

public:
  gxThread_t *t[NUMTHREADS];
};

void *SimpleThread::ThreadEntryRoutine(gxThread_t *thread)
{
  cout << "Entering thread" << "\n" << flush;
  mutex.MutexLock();
  
  //********** Critical Section *******************//
  cout << "Start critical section, holding lock" << "\n" << flush;

  // Access to shared data goes here 
  ++sharedData1; --sharedData2;
  cout << "sharedData1 = " << sharedData1 << ", sharedData2 = " << sharedData2
       << "\n" << flush;
  
  cout << "End critical section, release lock" << "\n" << flush;
  //********** Critical Section *******************//

  mutex.MutexUnlock();
  return 0;
}

void SimpleThread::Begin()
{
  for(int i = 0; i < NUMTHREADS; ++i) t[i] = CreateThread();
}

void SimpleThread::End()
{
  for(int i = 0; i < NUMTHREADS; ++i) JoinThread(t[i]);
}

SimpleThread::~SimpleThread()
{
  for(int i = 0; i < NUMTHREADS; ++i) {
    if(t[i]) delete t[i];
  }
}

int main()
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  SimpleThread t;
  
  cout << "Hold Mutex to prevent access to shared data" << "\n" << flush;
  cout << "sharedData1 = " << sharedData1 << ", sharedData2 = " << sharedData2
       << "\n" << flush;
  
  mutex.MutexLock();
 
  cout << "Create/start threads" << "\n" << flush;
  t.Begin();
  
  cout << "Wait a until we are done with the shared data" << "\n" << flush;
  t.sSleep(3);

  cout << "Unlock shared data" << "\n" << flush;
  mutex.MutexUnlock();

  cout << "Wait for the threads to complete, and release their resources"
       << "\n" << flush;
  t.End();
  
  return 0; // Exit the process
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

 

Modern C++ (C++17)

examples_modern/threads/mutex/modern.cpp 49 lines
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

namespace {
std::mutex mtx;
int sharedData1 = 0;
int sharedData2 = 0;
}

void worker()
{
  std::cout << "Entering thread\n";
  std::scoped_lock lock(mtx);
  std::cout << "Start critical section, holding lock\n";
  ++sharedData1; --sharedData2;
  std::cout << "sharedData1 = " << sharedData1 << ", sharedData2 = "
            << sharedData2 << "\n";
  std::cout << "End critical section, release lock\n";
}

int main()
{
  const int NUMTHREADS = 3;
  std::vector<std::thread> threads;

  std::cout << "Hold Mutex to prevent access to shared data\n";
  std::unique_lock<std::mutex> lock(mtx);
  std::cout << "sharedData1 = " << sharedData1 << ", sharedData2 = "
            << sharedData2 << "\n";

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

  std::cout << "Wait until we are done with the shared data\n";
  std::this_thread::sleep_for(std::chrono::seconds(1));
  std::cout << "Unlock shared data\n";
  lock.unlock();

  std::cout << "Wait for the threads to complete\n";
  for(auto &t : threads) t.join();
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target threads_mutex
./build-modern/threads_mutex
# or without CMake:
g++ -std=c++17 -pthread -o threads_mutex examples_modern/threads/mutex/modern.cpp

Output of the modern program

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

Hold Mutex to prevent access to shared data
sharedData1 = 0, sharedData2 = 0
Create/start threads
Entering thread
Entering thread
Wait until we are done with the shared data
Entering thread
Unlock shared data
Wait for the threads to complete
Start critical section, holding lock
sharedData1 = 1, sharedData2 = -1
End critical section, release lock
Start critical section, holding lock
sharedData1 = 2, sharedData2 = -2
End critical section, release lock
Start critical section, holding lock
sharedData1 = 3, sharedData2 = -3
End critical section, release lock