DataReelDataReelC++ Transition Guide

Examples › Thread Examples

threads_thread_pool

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

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

Modern equivalent of the thread pool example. The standard library has no thread pool class (std::async may or may not use one), so this is the usual small pool: a fixed set of std::thread workers, a queue of std::function tasks protected by a std::mutex, and a std::condition_variable to wake the workers. submit() returns a std::future for the task's result, which replaces JoinThread(pool). The destructor stops and joins the workers, so there is nothing to destroy or rebuild 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.
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.
thrPool, CreateThreadPool()a small pool: std::thread workers, std::queue, std::condition_variable, std::packaged_taskC++11 (C++17 invoke_result)submit() returns a std::future; the destructor joins the workers.
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/thread_pool/testprog.cpp 104 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

// Turn console message on or off before the thread are created
int display_message = 1;

void PausePrg()
// Pause the program until enter is pressed
{
  cout << "\n" << flush;
  cout << "Press Enter to continue..." << "\n" << flush;
  cin.get();
}

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

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

  return 0;
}

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

  const unsigned NUM_WORKERS = 10;

  SimpleThread *t = new SimpleThread;
  thrPool *pool = new thrPool;

  unsigned i;
  for(i = 0; i < NUM_WORKERS; i++) {
    t->CreateThread(pool, (void *)i);
    t->sSleep(1);
  }

  t->JoinThread(pool);

  cout << "\n" << flush;
  cout << "Destroying the thread pool..." << "\n" << flush;
  t->DestroyThreadPool(pool);

  cout << "Creating anther pool of " << NUM_WORKERS << " threads" 
       << "\n" << flush;
  PausePrg();

  display_message = 0; // Do not display any console messages
  pool = t->CreateThreadPool(NUM_WORKERS);

  t->sSleep(1);
  cout << "\n" << flush;
  cout << "Rebuilding the pool" << "\n" << flush;
  t->RebuildThreadPool(pool);

  // Wait for the treads to finish before destroying the pool
  t->JoinThread(pool);

  cout << "\n" << flush;
  cout << "Destroying the thread pool..." << "\n" << flush;
  if(!pool->IsEmpty()) {
    t->DestroyThreadPool(pool);
  }
  else {
    cout << "The pool is empty" << "\n" << flush;
    // If DestroyThreadPool() is not called the pool will not be deleted
    delete pool; 
  }
  
  cout << "Exiting..." << "\n" << flush;
  delete t;

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


  

Modern C++ (C++17)

examples_modern/threads/thread_pool/modern.cpp 89 lines
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <type_traits>
#include <vector>

class ThreadPool {
public:
  explicit ThreadPool(unsigned n) {
    for(unsigned i = 0; i < n; i++) workers_.emplace_back([this] { run(); });
  }
  ~ThreadPool() {
    {
      std::lock_guard<std::mutex> lock(m_);
      stopping_ = true;
    }
    cv_.notify_all();
    for(auto &w : workers_) w.join();
  }
  ThreadPool(const ThreadPool &) = delete;
  ThreadPool &operator=(const ThreadPool &) = delete;

  template <class F>
  auto submit(F f) -> std::future<std::invoke_result_t<F>> {
    using R = std::invoke_result_t<F>;
    auto task = std::make_shared<std::packaged_task<R()>>(std::move(f));
    std::future<R> result = task->get_future();
    {
      std::lock_guard<std::mutex> lock(m_);
      tasks_.emplace([task] { (*task)(); });
    }
    cv_.notify_one();
    return result;
  }

private:
  void run() {
    for(;;) {
      std::function<void()> task;
      {
        std::unique_lock<std::mutex> lock(m_);
        cv_.wait(lock, [this] { return stopping_ || !tasks_.empty(); });
        if(stopping_ && tasks_.empty()) return;
        task = std::move(tasks_.front());
        tasks_.pop();
      }
      task();
    }
  }
  std::vector<std::thread> workers_;
  std::queue<std::function<void()>> tasks_;
  std::mutex m_;
  std::condition_variable cv_;
  bool stopping_ = false;
};

int main()
{
  const unsigned NUM_WORKERS = 4;
  const unsigned NUM_TASKS = 10;
  std::mutex out;

  {
    ThreadPool pool(NUM_WORKERS);
    std::vector<std::future<unsigned>> results;
    for(unsigned i = 0; i < NUM_TASKS; i++) {
      results.push_back(pool.submit([i, &out] {
        std::lock_guard<std::mutex> lock(out);
        std::cout << "Executing worker task: " << i << "\n";
        return i * i;
      }));
    }
    unsigned sum = 0;
    for(auto &r : results) sum += r.get(); // Wait for every task
    std::cout << "Sum of the results: " << sum << "\n";
    std::cout << "Destroying the thread pool...\n";
  } // ~ThreadPool() joins the workers

  std::cout << "Exiting...\n";
  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_thread_pool
./build-modern/threads_thread_pool
# or without CMake:
g++ -std=c++17 -pthread -o threads_thread_pool examples_modern/threads/thread_pool/modern.cpp

Output of the modern program

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

Executing worker task: 0
Executing worker task: 1
Executing worker task: 2
Executing worker task: 3
Executing worker task: 4
Executing worker task: 5
Executing worker task: 6
Executing worker task: 7
Executing worker task: 8
Executing worker task: 9
Sum of the results: 285
Destroying the thread pool...
Exiting...