Examples › Thread Examples
threads_thread_security
C++20 or laterC++ standard library onlyPortable C++ (tested on Linux)
Legacy: examples_threads/thread_security/testprog.cpp · Modern: examples_modern/threads/thread_security/modern.cpp
Modern equivalent of the 6.4.1 thread checks. The legacy program checks that gxThread reports the right state, keeps a cancel, sleeps for the time asked and that gxCondition::ConditionTimedWait() waits for the time asked. This program checks the same properties of the standard library calls that replace them:
state A std::thread is joinable as soon as its constructor returns.
cancel A stop requested at once on a std::jthread is seen by the
thread (stop_requested()) and the request is kept.
sleep std::this_thread::sleep_for() sleeps at least the time asked.
timedwait std::condition_variable::wait_for() with no notify waits at
least the time asked, including a part of a second written
in nanoseconds that is one second or more.
The standard clocks used here are steady_clock (monotonic), so a change of the system time does not change the waits.
Returns 0 if every check passes.
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. |
| CancelThread(), ThreadCleanupHandler() | std::jthread::request_stop() + std::stop_token; cleanup in a destructor | C++20 | Cancellation is cooperative: the thread checks stop_requested() or waits on a condition_variable_any with the token. |
| 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. |
| gxMutex, MutexLock()/MutexUnlock() | std::mutex + std::scoped_lock / std::lock_guard / std::unique_lock | C++11 / C++17 | The lock is released by a destructor on every path, so a return cannot leave it locked. |
| gxCondition, ConditionWait()/ConditionSignal() | std::condition_variable wait(lock, predicate) / notify_one() | C++11 | The predicate form handles spurious wake ups. |
| ConditionTimedWait() | std::condition_variable::wait_for() / wait_until() | C++11 | Waits use std::chrono::steady_clock. |
| SetWidth(), SetFill(), Precision(), sprintf() | std::format("{:*>10} {:.3f}", ...) | C++20 | C++17 and older: <iomanip> setw, setfill, setprecision. |
| strcpy(), strncpy(), memmove() into char arrays | std::string; std::array<char, N> + string_view::copy() | C++11 / C++17 |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_threads/thread_security/testprog.cpp 184 lines
#include "gxdlcode.h" #include <stdio.h> #include <string.h> #include "gxthread.h" #include "gxmutex.h" #include "gxcond.h" #if defined (__POSIX__) #include <unistd.h> #include <signal.h> #include <time.h> #include <sys/wait.h> #include <sys/time.h> static int failures = 0; static void check(int ok, const char *what) { printf("%s %s\n", ok ? "PASS" : "FAIL", what); fflush(stdout); if(!ok) failures++; } typedef int (*TestFunc)(); static void run(const char *name, TestFunc f, int max_seconds = 60) { fflush(stdout); pid_t pid = fork(); if(pid == 0) { alarm(max_seconds); int rv = f(); fflush(stdout); _exit(rv); } int status = 0; waitpid(pid, &status, 0); if(WIFSIGNALED(status)) { char sbuf[256]; sprintf(sbuf, "%s (killed by signal %d)", name, WTERMSIG(status)); check(0, sbuf); return; } check(WIFEXITED(status) && WEXITSTATUS(status) == 0, name); } static double now_ms() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000.0 + ts.tv_nsec / 1000000.0; } class QuickThread : public gxThread { private: void *ThreadEntryRoutine(gxThread_t *thread) { return 0; } }; class WaitThread : public gxThread { private: void *ThreadEntryRoutine(gxThread_t *thread) { for(;;) sleep(1); // sleep() is a cancellation point return 0; } }; static int test_state() { const int rounds = 2000; int seen_new = 0; QuickThread t; for(int i = 0; i < rounds; i++) { gxThread_t *thread = t.CreateThread(); if(!thread || thread->GetThreadError() != gxTHREAD_NO_ERROR) return 2; if(thread->GetThreadState() == gxTHREAD_STATE_NEW) seen_new++; t.JoinThread(thread); delete thread; } if(seen_new) { printf(" %d of %d threads were NEW after CreateThread() returned\n", seen_new, rounds); return 1; } return 0; } static int test_cancel() { const int rounds = 500; int lost = 0; WaitThread t; for(int i = 0; i < rounds; i++) { gxThread_t *thread = t.CreateThread(); if(!thread || thread->GetThreadError() != gxTHREAD_NO_ERROR) return 2; if(t.CancelThread(thread) != 0) return 2; t.JoinThread(thread); if(thread->GetThreadState() != gxTHREAD_STATE_CANCELED) lost++; delete thread; } if(lost) { printf(" %d of %d canceled threads did not end CANCELED\n", lost, rounds); return 1; } return 0; } static void on_alarm(int) { } static int test_sleep() { QuickThread t; int rv = 0; for(int i = 0; i < 200; i++) t.mSleep(1); // Many calls, each its own objects double s = now_ms(); t.mSleep(300); double e = now_ms() - s; if(e < 300 || e > 1300) { printf(" mSleep(300) took %.0f ms\n", e); rv = 1; } s = now_ms(); t.uSleep(1200000); // 1.2 seconds: more than a second in microseconds e = now_ms() - s; if(e < 1200 || e > 2200) { printf(" uSleep(1200000) took %.0f ms\n", e); rv = 1; } s = now_ms(); t.nSleep(250000000UL); e = now_ms() - s; if(e < 250 || e > 1250) { printf(" nSleep(250000000) took %.0f ms\n", e); rv = 1; } // A signal in the middle of the sleep: the sleep goes on struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = on_alarm; sigaction(SIGALRM, &sa, 0); struct itimerval it; memset(&it, 0, sizeof(it)); it.it_value.tv_usec = 100000; setitimer(ITIMER_REAL, &it, 0); s = now_ms(); t.mSleep(500); e = now_ms() - s; if(e < 500) { printf(" mSleep(500) with a signal took %.0f ms\n", e); rv = 1; } return rv; } static int test_timedwait() { int rv = 0; gxMutex m; gxCondition c; if(m.MutexLock() != 0) return 2; double s = now_ms(); c.ConditionTimedWait(&m, 1, 0); double e = now_ms() - s; if(e < 1000 || e > 2000) { printf(" 1 s timed wait took %.0f ms\n", e); rv = 1; } s = now_ms(); c.ConditionTimedWait(&m, 0, 1500000000UL); e = now_ms() - s; if(e < 1500 || e > 2500) { printf(" 1.5e9 ns timed wait took %.0f ms\n", e); rv = 1; } m.MutexUnlock(); return rv; } int main() { run("state: RUNNING when CreateThread() returns", test_state); run("cancel: a thread canceled at once stays CANCELED", test_cancel); run("sleep: mSleep(), uSleep() and nSleep() sleep the time asked", test_sleep); run("timedwait: ConditionTimedWait() waits the time asked", test_timedwait); printf("%d failure(s)\n", failures); return failures ? 1 : 0; } #else // Not POSIX int main() { printf("SKIP: the thread checks use fork()\n"); return 0; } #endif // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++20)
examples_modern/threads/thread_security/modern.cpp 78 lines
#include <chrono> #include <condition_variable> #include <iostream> #include <mutex> #include <stop_token> #include <thread> using namespace std::chrono; static int failures = 0; static void check(bool ok, const char *what) { std::cout << (ok ? "PASS: " : "FAIL: ") << what << "\n"; if(!ok) failures++; } static double elapsed_ms(steady_clock::time_point start) { return duration<double, std::milli>(steady_clock::now() - start).count(); } int main() { // state { std::thread t([] {}); check(t.joinable(), "state: joinable after the constructor returns"); t.join(); check(!t.joinable(), "state: not joinable after join()"); } // cancel { bool seen = false; std::jthread t([&seen](std::stop_token st) { while(!st.stop_requested()) std::this_thread::yield(); seen = true; }); t.request_stop(); t.join(); check(seen, "cancel: stop seen by the thread"); check(t.get_stop_token().stop_requested(), "cancel: request kept"); } // sleep { auto start = steady_clock::now(); std::this_thread::sleep_for(milliseconds(200)); check(elapsed_ms(start) >= 200.0, "sleep: sleep_for(200ms)"); start = steady_clock::now(); std::this_thread::sleep_for(microseconds(150000)); check(elapsed_ms(start) >= 150.0, "sleep: sleep_for(150000us)"); start = steady_clock::now(); std::this_thread::sleep_for(nanoseconds(120000000)); check(elapsed_ms(start) >= 120.0, "sleep: sleep_for(120000000ns)"); } // timedwait { std::mutex m; std::condition_variable cv; std::unique_lock<std::mutex> lock(m); auto start = steady_clock::now(); cv.wait_for(lock, milliseconds(250), [] { return false; }); check(elapsed_ms(start) >= 250.0, "timedwait: wait_for(250ms)"); start = steady_clock::now(); cv.wait_for(lock, nanoseconds(1100000000), [] { return false; }); check(elapsed_ms(start) >= 1100.0, "timedwait: wait_for(1100000000ns)"); } std::cout << (failures ? "FAILED" : "All checks passed") << "\n"; return failures ? 1 : 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Build and run
cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20 cmake --build build-modern --target threads_thread_security ./build-modern/threads_thread_security # or without CMake: g++ -std=c++20 -pthread -o threads_thread_security examples_modern/threads/thread_security/modern.cpp
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
PASS: state: joinable after the constructor returns PASS: state: not joinable after join() PASS: cancel: stop seen by the thread PASS: cancel: request kept PASS: sleep: sleep_for(200ms) PASS: sleep: sleep_for(150000us) PASS: sleep: sleep_for(120000000ns) PASS: timedwait: wait_for(250ms) PASS: timedwait: wait_for(1100000000ns) All checks passed