chsvlib
chsv helper source code
chsvthrd\chsv_thread_local_2.cpp

Demonstrates a usage and an effect of the chsv_thread_local macro.

#include <thread>
#include <mutex>
#include <iostream>
#include <vector>
#include "chsvthrd.h"
chsv_thread_local(int, file_scope) = 2;
int main(int, char**)
{
const unsigned int threads = 8;
//file_scope = 1;
static chsv_thread_local(int, block_scope) = file_scope;
std::mutex io_lock;
std::cout << "Initial values:\n\tfile_scope = " << file_scope << "\n\tblock_scope = " << block_scope << std::endl;
++file_scope; ++block_scope;
auto thr = [&]()->void
{
std::lock_guard<std::mutex> lock(io_lock);
++file_scope; ++block_scope;
std::cout << "A thread " << std::this_thread::get_id() <<
" with values captured by value:\n\tfile_scope = " << file_scope << "\n\tblock_scope = " << block_scope << std::endl;
};
std::vector<std::thread> vec;
for (unsigned i = 0; i < threads; ++i)
vec.emplace_back(thr);
for (auto& it:vec)
it.join();
std::wcout << "All threads terminated." << std::endl;
std::cout << "Final values:\n\tfile_scope = " << file_scope << "\n\tblock_scope = " << block_scope << std::endl;
return 0;
}
/*
Output:
=======
Initial values:
file_scope = 2
block_scope = 2
A thread 2 with values captured by value:
file_scope = 3
block_scope = 1
A thread 3 with values captured by value:
file_scope = 3
block_scope = 1
A thread 6 with values captured by value:
file_scope = 3
block_scope = 1
A thread 7 with values captured by value:
file_scope = 3
block_scope = 1
A thread 8 with values captured by value:
file_scope = 3
block_scope = 1
A thread 4 with values captured by value:
file_scope = 3
block_scope = 1
A thread 9 with values captured by value:
file_scope = 3
block_scope = 1
A thread 5 with values captured by value:
file_scope = 3
block_scope = 1
All threads terminated.
Final values:
file_scope = 3
block_scope = 3
*/
#define chsv_thread_local(type, name)
A macro simplifying work with thread-specific storages. It is introduced to implement syntax similar ...
Definition: chsvthrd.h:1565
An interface for the portable implementation of threads as defined in C11 standard supplemented with ...