Threads in C++ Flashcards
Which version of C++ are threads available from?
include class is included in C++ 11.
Main thread
For every application there is a main thread running.
Threads
A thread is a path of execution within a process. A process can contain multiple threads.
Why multithreading?
A thread is also known as lightweight process. The idea is to achieve parallelism by dividing a process into multiple threads
Process vs Thread?
The primary difference is that threads within the same process run in a shared memory space, while processes run in separate memory spaces.
Threads are not independent of one another like processes are, and as a result threads share with other threads their code section, data section, and OS resources (like open files and signals). But, like process, a thread has its own program counter (PC), register set, and stack space.
How threads work in C++?
std: :thread t1(func, parameters);
t1. join()
t1. detach();
or
if(t1.joinable)
t1.join()
Mutex in C++
include
std::mutex m;
m.lock()
critical section
m.unlock();
Mutex try_lock()
tries to block the mutex. Returns true if the lock was free and granted else returns false immediately.
Non-blocking.
try_lock(m1, m2, m3,..)
Not an object of mutex, global function. Tries to block all the mutable objects passed to it.
Recursive Mutex in C++
Used to lock recursive methods.
std::recursive_mutex m1;
Timed Mutex in C++
Gives an option of locking the mutex for certain time period.
std: :timed_mutex m
m. try_lock_for(std::chrono::seconds(1))
lock guard in C++
Lightweight wrapper for owning mutex on scope basis.
std::lock_guard lock(m)
unique_lock in C++
Wrapper over mutex. You can have different locking strategies. Time constraint attempts at locking. Can notify threads waiting for thread.
future and promise in C++
std: :promise promise obj1;
std: :future obj2 = obj1.get_future();
std::async in C++
it runs a function asynchronously. and returns a std::future that will hold the value. You can specify the launch policy.