Examples › Thread Examples
threads_stack
C++11 or laterC++ standard library onlyPortable C++ (tested on Linux)
Legacy: examples_threads/stack/testprog.cpp · Modern: examples_modern/threads/stack/modern.cpp
Modern equivalent of the stack size example. std::thread cannot set a stack size (the C++ standard has no thread attributes; std::jthread does not add them). A program that needs a bigger or smaller stack still uses the platform call. This program keeps that in one small function that runs any std::function on a POSIX thread with the stack size asked, and returns a std::thread-like joinable object. On Windows the same is done with the stack size argument of _beginthreadex().
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. |
| DestroyThread(), delete gxThread_t | nothing: the std::thread object owns the thread | C++11 | Join 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. |
| CreateThread(..., stack size) | pthread_attr_setstacksize() / _beginthreadex() | platform | std::thread cannot set a stack size. |
| 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/stack/testprog.cpp 83 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() << ", Stack Size: " << thread->GetStackSize() << "\n" << flush; return 0; } int main() { #ifdef __MSVC_DEBUG__ InitLeakTest(); #endif const unsigned NUM_THREADS = 10; gxStackSizeType ssize = 4096; gxThreadType type = gxTHREAD_TYPE_JOINABLE; #if defined (__POSIX__) ssize *= 5; // Min size under POSIX is 16K #endif SimpleThread *t = new SimpleThread; gxThread_t *thread[NUM_THREADS]; unsigned i; cout << "Creating " << NUM_THREADS << " threads" << "\n" << flush; cout << "New stack size per thread = " << ssize << "\n" << flush; for(i = 0; i < NUM_THREADS; i++) { thread[i] = t->CreateThread((void *)i, type, ssize); // Check for any errors if(thread[i]->GetThreadError() != gxTHREAD_NO_ERROR) cout << thread[i]->ThreadExceptionMessage() << "\n" << flush; // Allow the threads to print their messages in order t->sSleep(1); } // Wait for the all treads to finish for(i = 0; i < NUM_THREADS; i++) t->JoinThread(thread[i]); 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++11)
examples_modern/threads/stack/modern.cpp 74 lines
#include <functional> #include <iostream> #include <memory> #include <system_error> #include <vector> #if defined(__unix__) #include <limits.h> #include <pthread.h> #endif #if defined(__unix__) class SizedThread { public: SizedThread(std::size_t stack_size, std::function<void()> fn) : fn_(new std::function<void()>(std::move(fn))) { pthread_attr_t attr; pthread_attr_init(&attr); const std::size_t min_size = PTHREAD_STACK_MIN; if(stack_size < min_size) stack_size = min_size; pthread_attr_setstacksize(&attr, stack_size); int rv = pthread_create(&tid_, &attr, &SizedThread::run, fn_.get()); pthread_attr_destroy(&attr); if(rv != 0) throw std::system_error(rv, std::generic_category()); joinable_ = true; } SizedThread(const SizedThread &) = delete; SizedThread &operator=(const SizedThread &) = delete; SizedThread(SizedThread &&o) noexcept : tid_(o.tid_), fn_(std::move(o.fn_)), joinable_(o.joinable_) { o.joinable_ = false; } ~SizedThread() { join(); } void join() { if(joinable_) { pthread_join(tid_, nullptr); joinable_ = false; } } private: static void *run(void *p) { (*static_cast<std::function<void()> *>(p))(); return nullptr; } pthread_t tid_{}; std::unique_ptr<std::function<void()>> fn_; bool joinable_ = false; }; #endif int main() { #if defined(__unix__) const unsigned NUM_THREADS = 10; const std::size_t ssize = 4096 * 5; // Min size under POSIX is 16K std::cout << "Creating " << NUM_THREADS << " threads\n"; std::cout << "New stack size per thread = " << ssize << "\n"; for(unsigned i = 0; i < NUM_THREADS; i++) { SizedThread t(ssize, [i] { pthread_attr_t attr; std::size_t size = 0; pthread_getattr_np(pthread_self(), &attr); // GNU extension pthread_attr_getstacksize(&attr, &size); pthread_attr_destroy(&attr); std::cout << "Executing thread: " << i << ", Stack Size: " << size << "\n"; }); t.join(); // Keep the output in order } std::cout << "Exiting...\n"; #else std::cout << "This example uses POSIX threads; see the comments.\n"; #endif 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_stack ./build-modern/threads_stack # or without CMake: g++ -std=c++11 -pthread -o threads_stack examples_modern/threads/stack/modern.cpp
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
Creating 10 threads New stack size per thread = 20480 Executing thread: 0, Stack Size: 20480 Executing thread: 1, Stack Size: 20480 Executing thread: 2, Stack Size: 20480 Executing thread: 3, Stack Size: 20480 Executing thread: 4, Stack Size: 20480 Executing thread: 5, Stack Size: 20480 Executing thread: 6, Stack Size: 20480 Executing thread: 7, Stack Size: 20480 Executing thread: 8, Stack Size: 20480 Executing thread: 9, Stack Size: 20480 Exiting...