DataReelDataReelC++ Transition Guide

Examples › Thread Examples

threads_specific

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

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

Modern equivalent of the thread-specific data example. The C++11 thread_local storage class replaces gxThreadKey, ThreadKeyCreate(), ThreadSetSpecific(), ThreadGetSpecific() and ThreadKeyDelete(). Each thread has its own copy of a thread_local variable, constructed in that thread and destroyed when the thread ends, so nothing is new'd, cast from void * or deleted by hand.

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.
ExitThread(), GetThreadExitCode()return a value; std::async / std::future::get()C++11An exception thrown in the thread comes out of get().
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.
gxThreadKey, ThreadSetSpecific()/ThreadGetSpecific()thread_local variablesC++11One copy per thread, built in the thread and destroyed when it ends.
gxThread_t IDs and state messagesstd::thread::id, std::this_thread::get_id(); program-owned std::atomic stateC++11
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/specific/testprog.cpp 140 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

// Constants
const int NUM_THREADS = 2;
 
// Thread specific data used in this process
struct threadSpecific_data_t
{
  threadSpecific_data_t(int i, int j) {
    threadSpecific1 = i; threadSpecific2 = j; 
  }
  
  int threadSpecific1;
  int threadSpecific2;
};

// Thread key
gxThreadKey threadSpecificKey;

class SimpleThread : public gxThread
{
public:
  SimpleThread () { oid = 1; }
  
private: // Base class interface
  void *ThreadEntryRoutine(gxThread_t *thread);
  void ThreadExitRoutine(gxThread_t *thread);
  
private: // Functions that use the threadSpecific data
  void foo(gxThread_t *thread);  
  void bar(gxThread_t *thread);

private:
  gxThreadObjectID oid;
};

void *SimpleThread::ThreadEntryRoutine(gxThread_t *thread)
// Thread's entry function
{
  thread->SetObjectID(oid++);
  cout << "Entering thread: " << thread->GetObjectID() << "\n" << flush;
  
  threadSpecific_data_t *gData = \
    (threadSpecific_data_t *)thread->GetThreadParm();

  if(ThreadSetSpecific(threadSpecificKey, gData) != 0) {
    cout << "Thread local storage error" << "\n" << flush;
    return ExitThread(thread, 1);
  }
  
  foo(thread);
  return 0;
}
 
void SimpleThread::foo(gxThread_t *thread)
{
  threadSpecific_data_t *gData = \
    (threadSpecific_data_t *)ThreadGetSpecific(threadSpecificKey);

  cout << "Thread: " << thread->GetObjectID() << " entering foo(), ";
  cout << "threadSpecific data = " << gData->threadSpecific1 << ' '
       << gData->threadSpecific2
       << "\n" << flush;

  bar(thread);
}
 
void SimpleThread::bar(gxThread_t *thread)
{
  threadSpecific_data_t *gData = \
    (threadSpecific_data_t *)ThreadGetSpecific(threadSpecificKey);
  
  cout << "Thread: " << thread->GetObjectID() << " entering bar(), ";
  cout << "threadSpecific data = " << gData->threadSpecific1 << ' '
       << gData->threadSpecific2
       << "\n" << flush;
}
 
void SimpleThread::ThreadExitRoutine(gxThread_t *thread)
{
  cout << "Thread: " << thread->GetObjectID() << " exiting" << "\n" << flush;

  void *parm = thread->GetThreadParm();

  // Free the local storage resources
  delete parm;
}
 
int main()
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  SimpleThread t;
  gxThread_t *thread[NUM_THREADS];

  if(t.ThreadKeyCreate(threadSpecificKey) != 0) {
    cout << "Thread local storage error!" << "\n" << flush;
    cout << "Could not obtain and index." << "\n" << flush;
    return 1;
  }

  cout << "Creating " << NUM_THREADS << " threads" << "\n" << flush;
  int i;
  for(i = 0; i < NUM_THREADS; i++) {
    // Create per-thread threadSpecific data and pass it to the thread
    threadSpecific_data_t *gData = new threadSpecific_data_t(i, ((i+1)*2));
    thread[i] = t.CreateThread((void *)gData);
    t.sSleep(1); // Allow the thread to print their messages in order
  }
 
  cout << "Wait for the threads to complete, and release their resources"
       << "\n" << flush;
  for(i = 0; i < NUM_THREADS; i++) t.JoinThread(thread[i]);

  // Release the index
  t.ThreadKeyDelete(threadSpecificKey);

  // Prevent memory leaks
  for(i = 0; i < NUM_THREADS; i++) delete thread[i];
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++11)

examples_modern/threads/specific/modern.cpp 62 lines
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

struct ThreadSpecificData {
  int value1 = 0;
  int value2 = 0;
  int object_id = 0;
};

thread_local ThreadSpecificData tls; // One per thread
std::mutex out;

void bar()
{
  std::lock_guard<std::mutex> lock(out);
  std::cout << "Thread: " << tls.object_id << " entering bar(), "
            << "threadSpecific data = " << tls.value1 << ' ' << tls.value2
            << "\n";
}

void foo()
{
  {
    std::lock_guard<std::mutex> lock(out);
    std::cout << "Thread: " << tls.object_id << " entering foo(), "
              << "threadSpecific data = " << tls.value1 << ' ' << tls.value2
              << "\n";
  }
  bar();
}

void entry(int i)
{
  tls.value1 = i;          // ThreadSetSpecific(): just assign
  tls.value2 = (i + 1) * 2;
  tls.object_id = i + 1;
  {
    std::lock_guard<std::mutex> lock(out);
    std::cout << "Entering thread: " << tls.object_id << "\n";
  }
  foo();
  std::lock_guard<std::mutex> lock(out);
  std::cout << "Thread: " << tls.object_id << " exiting\n";
}

int main()
{
  const int NUM_THREADS = 2;
  std::vector<std::thread> threads;
  std::cout << "Creating " << NUM_THREADS << " threads\n";
  for(int i = 0; i < NUM_THREADS; i++) threads.emplace_back(entry, i);
  for(auto &t : threads) t.join();
  std::cout << "main() has its own copy: " << tls.value1 << ' '
            << tls.value2 << "\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_specific
./build-modern/threads_specific
# or without CMake:
g++ -std=c++11 -pthread -o threads_specific examples_modern/threads/specific/modern.cpp

Output of the modern program

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

Creating 2 threads
Entering thread: 1
Thread: 1 entering foo(), threadSpecific data = 0 2
Thread: 1 entering bar(), threadSpecific data = 0 2
Thread: 1 exiting
Entering thread: 2
Thread: 2 entering foo(), threadSpecific data = 1 4
Thread: 2 entering bar(), threadSpecific data = 1 4
Thread: 2 exiting
main() has its own copy: 0 0