Concurrency and Source Panels
Thread Local Context
Keep per-thread state with thread_local storage.
Thread Local Context
thread_local_context.cpp
#include <iostream>
#include <thread>
thread_local int localScore = 0;
void writeLocalScore(int boost, int offset, int* output) {
localScore = boost + offset;
*output = localScore;
}
int main() {
int boost = ;
int firstScore = 0;
int secondScore = 0;
std::thread first(writeLocalScore, boost, 10, &firstScore);
std::thread second(writeLocalScore, boost, 20, &secondScore);
first.join();
second.join();
int total = firstScore + secondScore;
std::cout << "boost=" << boost << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
#include <thread>
thread_local int localScore = 0;
void writeLocalScore(int boost, int offset, int* output) {
localScore = boost + offset;
*output = localScore;
}
int main() {
int boost = ;
int firstScore = 0;
int secondScore = 0;
std::thread first(writeLocalScore, boost, 10, &firstScore);
std::thread second(writeLocalScore, boost, 20, &secondScore);
first.join();
second.join();
int total = firstScore + secondScore;
std::cout << "boost=" << boost << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
#include <thread>
thread_local int localScore = 0;
void writeLocalScore(int boost, int offset, int* output) {
localScore = boost + offset;
*output = localScore;
}
int main() {
int boost = ;
int firstScore = 0;
int secondScore = 0;
std::thread first(writeLocalScore, boost, 10, &firstScore);
std::thread second(writeLocalScore, boost, 20, &secondScore);
first.join();
second.join();
int total = firstScore + secondScore;
std::cout << "boost=" << boost << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
local
Each thread has its own copy of a `thread_local` variable.
merge
The main thread merges the values after both worker threads finish.