thread Flashcards
What option do we need to compile thread application?
-pthread
Ex: g++ -pthread -g -o hello.out hellp.cpp
How many way can we construct a thread?
A function pointer
A function object
A lambda expression
How to get current thread id?
this_thread::get_id()
How to create atomic variable?
How to update atomic variable and make sure other did not update that value?
How to make cout thread-safe?
cout.sync_with_stdio(true);
How and Why using thread local?
Each thread can have its own static variable
static thread_local int mismatch_count;
What is the lock_guard?
The class lock_guard is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block.
When a lock_guard object is created, it attempts to take ownership of the mutex it is given. When control leaves the scope in which the lock_guard object was created, the lock_guard is destructed and the mutex is released.
How condition_variable with “wait” method work?
before calling “wait”, the thread should already acquired that lock. When “wait” execute, it will call unlock() then block the thread
What is the difference between unique_lock and lock_guard?
We can construct unique_lock without acquire the mutex by passing defered_lock and call lock later.
what is call_once used for?
to make sure that the function will get called only one time, no matter how many threads try to call the same call_once().
We used it for initialization with multi-thread
Can we copy unique_lock?
No but we can move
Can we call std::async and not create a thread?
Yes, by passing std::launch::deferred
auto fut = async(launch::deferred, process_something);
auto x = fut.get(); // create thread this time.
How to use async instead of thread, cond, mutex
the following code will create 10 threads that execute “divide” function and return value will keep in “future” object that store in vector all_tasks.
We can get the result later.
How to use promise to send data to child thread?
- on the caller, create promise object then get future object from that
- pass that future object in async
- on the function parameter, declare future object
- in that function (child thread) call future object to get value
- on the caller later one then call promise object “set_value”