DataReelDataReelC++ Transition Guide

Examples › Thread Examples

threads_detach

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

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

Modern equivalent of the detach example. std::thread::detach() replaces gxTHREAD_TYPE_DETACHED. A detached thread cannot be joined, so the legacy program sleeps and hopes the threads are done. C++20 std::latch lets main() wait until every detached thread has counted down, which is exact. Errors from thread creation are std::system_error exceptions instead of GetThreadError() codes.

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.
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.
gxTHREAD_TYPE_DETACHEDt.detach(); std::latch to wait for the workC++11 / C++20A latch replaces 'sleep and hope the threads are done'.
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/detach/testprog.cpp 75 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"

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

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

void *SimpleThread::ThreadEntryRoutine(gxThread_t *thread)
// Thread's entry function
{
  cout << "Executing thread: " << (long)(size_t)thread->GetThreadParm() << ", "
       << thread->ThreadTypeMessage() << '\n' << flush;
    
  return 0;
}

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

  const unsigned NUM_THREADS = 10;

  gxThreadType type = gxTHREAD_TYPE_DETACHED;
  
  SimpleThread *t = new SimpleThread;
  gxThread_t *thread[NUM_THREADS];
  
  unsigned i;
  cout << "Creating " << NUM_THREADS << " threads" << "\n" << flush;
  for(i = 0; i < NUM_THREADS; i++) {
    thread[i] = t->CreateThread((void *)i, type);

    // Check for any errors
    if(thread[i]->GetThreadError() != gxTHREAD_NO_ERROR)
      cout << thread[i]->ThreadExceptionMessage() << "\n" << flush;
    
    // Allow the threads to print there messages in order
    t->sSleep(1);
  }

  cout << "Waiting for the all threads to finish..." << "\n" << flush;
  t->sSleep(3);

  cout << "\n" << flush;
  cout << "Destroying all the threads..." << "\n" << flush;
  for(i = 0; i < NUM_THREADS; i++) t->DestroyThread(thread[i]);

  cout << "Exiting..." << "\n" << flush;

  delete t;
  return 0; // Exit the process, terminating all threads
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //


  

Modern C++ (C++20)

examples_modern/threads/detach/modern.cpp 38 lines
#include <iostream>
#include <latch>
#include <mutex>
#include <system_error>
#include <thread>

int main()
{
  const unsigned NUM_THREADS = 10;
  std::latch done(NUM_THREADS);
  std::mutex out; // Keeps each line in one piece

  std::cout << "Creating " << NUM_THREADS << " threads\n";
  for(unsigned i = 0; i < NUM_THREADS; i++) {
    try {
      std::thread([i, &done, &out] {
        {
          std::lock_guard<std::mutex> lock(out);
          std::cout << "Executing thread: " << i << ", detached\n";
        }
        done.count_down(); // Last use of shared state in this thread
      }).detach();
    }
    catch(const std::system_error &e) {
      std::cout << "Could not create thread " << i << ": " << e.what() << "\n";
      done.count_down();
    }
  }

  std::cout << "Waiting for the all threads to finish...\n";
  done.wait(); // Instead of sSleep(3)
  std::cout << "Exiting...\n";
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

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

Output of the modern program

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

Creating 10 threads
Executing thread: 0, detached
Executing thread: 1, detached
Executing thread: 4, detached
Executing thread: 2, detached
Executing thread: 5, detached
Executing thread: 3, detached
Executing thread: 6, detached
Executing thread: 8, detached
Waiting for the all threads to finish...
Executing thread: 9, detached
Executing thread: 7, detached
Exiting...