CppCommon  1.0.4.1
C++ Common Library
threads_thread.cpp

Thread example

#include "threads/thread.h"
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char** argv)
{
// Initialize stack trace manager of the current process
// Setup exceptions handler for the current process
std::cout << "Press Enter to stop..." << std::endl;
// Prepare thread CPU affinity bitsets (odd and even)
std::bitset<64> affinity1(0x5555555555555555ull);
std::bitset<64> affinity2(0xAAAAAAAAAAAAAAAAull);
// Start some threads
std::atomic<bool> stop(false);
std::vector<std::thread> threads;
for (int thread = 0; thread < 8; ++thread)
{
// Start thread with an exception handler registered
std::thread thrd = CppCommon::Thread::Start([&lock, &stop, thread]()
{
while (!stop)
{
// Use locker with critical section to protect the output
{
std::cout << "Thread Number: " << thread << ", Thread Id: " << CppCommon::Thread::CurrentThreadId() << ", Thread CPU affinity: " << CppCommon::Thread::CurrentThreadAffinity() << std::endl;
}
// Sleep for one second...
}
});
// Set thread CPU affinity
CppCommon::Thread::SetAffinity(thrd, ((thread % 2) == 0) ? affinity1 : affinity2);
// Add the created thread to the collection
threads.emplace_back(std::move(thrd));
}
// Wait for input
std::cin.get();
// Stop threads
stop = true;
// Wait for all threads
for (auto& thread : threads)
thread.join();
return 0;
}
Critical section synchronization primitive.
static void SetupProcess()
Setup exceptions handler for the current process.
Locker synchronization primitive.
Definition: locker.h:23
static void Initialize()
Initialize stack trace manager.
static uint64_t CurrentThreadId() noexcept
Get the current thread Id.
Definition: thread.cpp:60
static void Sleep(int64_t milliseconds) noexcept
Sleep the current thread for the given milliseconds.
Definition: thread.h:94
static uint32_t CurrentThreadAffinity() noexcept
Get the current thread CPU affinity.
Definition: thread.cpp:71
static void SetAffinity(const std::bitset< 64 > &affinity)
Set the current thread CPU affinity bitset.
Definition: thread.cpp:254
static std::thread Start(Fn &&fn, Args &&... args)
Start a new thread with an exception handler registered.
Definition: thread.inl:45
Critical section synchronization primitive definition.
Exceptions handler definition.
Stack trace manager definition.
Thread definition.