Threading Flashcards
how to pass data
by pointer
thread(func, &arg)
void* func(int* args) { ++(*args);}
by reference
thread(func, std::ref(arg))
void* func(int &args) { ++args;}
user level thread and system level
user level more simple, no os needed
but cant force it to give up hw
pro: lightweight
con: no scheduling guarantees
usecase: light fine grained tasks
yield and spin locks
spin
thread will keep probind until lock free
fast, but uses more resources hw
yield
if locked it gives up hw
low resources, but slow and bad for hpc
lock granulairyt
coarse: one lock for everythign
easy, but low concurrency
fine: one lock for each data element
good concurrency, but deadlcoking
how to avoid lock deadlock
- order locks
- hold 1 lock at a time
- have a central arbiter (overhead)
code threads
include mutex
include thread
std::mutex mtx;
void func() {
mtx.lock;
var access
mtx.unlock(); }
main {
std::thread threads[10];
for (loop 10) {
threads[i] = std::thread(func, arg); }
for (auto &th: threads) {
th.join(); }