Examples › Thread Examples
threads_priority
C++17 or laterC++ standard library onlyPortable C++ (tested on Linux)
Legacy: examples_threads/priority/testprog.cpp · Modern: examples_modern/threads/priority/modern.cpp
Modern equivalent of the priority example. The standard library has no thread priorities. Two parts of the legacy program map to it:
- Running work in priority order: a std::priority_queue of tasks, taken by a worker thread, highest priority first.
- The operating system priority of a thread: std::thread gives the platform handle with native_handle(), for pthread_setschedparam() (POSIX) or SetThreadPriority() (Windows). On Linux a normal (SCHED_OTHER) thread has priority 0 and raising it needs privileges, so this program only reads it.
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| gxThread subclass, CreateThread() | std::thread t(callable, args...) | C++11 | Any function, lambda or functor runs in the thread; arguments are copied with their types (no void *). |
| JoinThread() | t.join(); std::future::get() | C++11 | join() 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. |
| SetThreadPriority() | t.native_handle() + pthread_setschedparam() / SetThreadPriority() | platform | The standard has no priorities; a std::priority_queue orders work. |
| thrPool, CreateThreadPool() | a small pool: std::thread workers, std::queue, std::condition_variable, std::packaged_task | C++11 (C++17 invoke_result) | submit() returns a std::future; the destructor joins the workers. |
| new / delete | automatic objects, containers, std::unique_ptr / std::make_unique | C++11 / C++14 | Ownership is in the type, and release() shows a hand-over. |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_threads/priority/testprog.cpp 84 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 worker thread: " << (long)(size_t)thread->GetThreadParm() << ", " << thread->ThreadPriorityMessage() << "\n" << flush; return 0; } int main() { #ifdef __MSVC_DEBUG__ InitLeakTest(); #endif const unsigned NUM_WORKERS = 10; SimpleThread *t = new SimpleThread; thrPool *pool = new thrPool; gxThread_t *thread[NUM_WORKERS]; unsigned i; // Construct some new threads without executing them for(i = 0; i < NUM_WORKERS; i++) thread[i] = t->ConstructThread((void *)i); // Change some of the thread priorities before placing them in the pool thread[NUM_WORKERS-1]->SetThreadPriority(gxTHREAD_PRIORITY_HIGH); thread[NUM_WORKERS-2]->SetThreadPriority(gxTHREAD_PRIORITY_HIGH); thread[NUM_WORKERS-3]->SetThreadPriority(gxTHREAD_PRIORITY_HIGH); thread[0]->SetThreadPriority(gxTHREAD_PRIORITY_LOW); thread[1]->SetThreadPriority(gxTHREAD_PRIORITY_LOW); thread[2]->SetThreadPriority(gxTHREAD_PRIORITY_LOW); // Put the threads in the thread pool for(i = 0; i < NUM_WORKERS; i++) pool->AddThread(thread[i]); // Execute all the threads in the pool thrPoolNode *ptr = pool->GetHead(); while(ptr) { t->CreateThread(ptr->GetThreadPtr()); t->sSleep(1); ptr = ptr->GetNext(); } // Wait for the treads to finish before destroying the pool t->JoinThread(pool); cout << "\n" << flush; cout << "Destroying the thread pool..." << "\n" << flush; t->DestroyThreadPool(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/priority/modern.cpp 59 lines
#include <functional> #include <iostream> #include <queue> #include <thread> #include <vector> #if defined(__unix__) #include <pthread.h> #endif enum class Priority { Low = 0, Normal = 1, High = 2 }; struct Task { Priority priority; unsigned id; bool operator<(const Task &other) const { // priority_queue: max first return priority < other.priority || (priority == other.priority && id > other.id); } }; const char *name(Priority p) { return p == Priority::High ? "high" : p == Priority::Low ? "low" : "normal"; } int main() { const unsigned NUM_WORKERS = 10; std::priority_queue<Task> tasks; for(unsigned i = 0; i < NUM_WORKERS; i++) { Priority p = Priority::Normal; if(i >= NUM_WORKERS - 3) p = Priority::High; if(i < 3) p = Priority::Low; tasks.push({p, i}); } std::thread worker([&tasks] { #if defined(__unix__) int policy = 0; sched_param sp{}; pthread_getschedparam(pthread_self(), &policy, &sp); std::cout << "Worker OS policy " << policy << ", priority " << sp.sched_priority << "\n"; #endif while(!tasks.empty()) { // Only this thread uses the queue now Task t = tasks.top(); tasks.pop(); std::cout << "Executing task: " << t.id << ", priority " << name(t.priority) << "\n"; } }); worker.join(); 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_priority ./build-modern/threads_priority # or without CMake: g++ -std=c++17 -pthread -o threads_priority examples_modern/threads/priority/modern.cpp
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
Worker OS policy 0, priority 0 Executing task: 7, priority high Executing task: 8, priority high Executing task: 9, priority high Executing task: 3, priority normal Executing task: 4, priority normal Executing task: 5, priority normal Executing task: 6, priority normal Executing task: 0, priority low Executing task: 1, priority low Executing task: 2, priority low Exiting...