1.spinlock
// spinLock.cpp
#include <atomic>
#include <thread>
class Spinlock{
std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock(){
while( flag.test_and_set(std::memory_order_acquire) );
}
void unlock(){
flag.clear(std::memory_order_release);
}
};
2.atomic condition
// atomicCondition.cpp
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
std::vector<int> mySharedWork;
std::atomic<bool> dataReady(false);
void waitingForWork(){
std::cout << "Waiting " << std::endl;
while (!dataReady.load(std::memory_order_acquire)){
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
mySharedWork[1] = 2;
std::cout << "Work done " << std::endl;
}
Memory Model 31
void setDataReady(){
mySharedWork = {1, 0, 3};
dataReady.store(true, std::memory_order_release);
std::cout << "Data prepared" << std::endl;
}
Push versus Pull Principle(条件变量和原子变量在线程阻塞中的区别)
I cheated a little. There is one key difference between the synchronisation of the threads with
a condition variable and
std::atomic<bool>
. The condition variable notifies the waiting
thread (
condVar.notify()
) that it should proceed with its work. The waiting thread with
std::atomic<bool>
checks if the sender is done with its work (
dataRead = true
).
The condition variable notifies the waiting thread (push principle) while the atomic boolean
repeatedly asks for the value (pull principle).
conditiaon variable是被动,而atomic boolean是主动。
3.variable lifetime(静态变量和线程局部变量的区别)
A static variable is bound to the lifetime of the main thread, a thread_local variable is
bound to the lifetime of its thread, and a local variable is bound to the lifetime of the scope in which
it was created.
4.condition_variable和promises futures
条件通知既可以使用condition variables,也可以使用promise futures。不同点在于:
condition varialbes:可以多次重复使用
promises futures:只能使用一次,对于使用一次的情况下,使用promises futures更简单,并且不会出现虚假唤醒或者漏掉唤醒。
// promiseFutureSynchronise.cpp
#include <future>
#include <iostream>
#include <utility>
void doTheWork(){
std::cout << "Processing shared data." << std::endl;
}
void waitingForWork(std::future<void>&& fut){
std::cout << "Worker: Waiting for work." << std::endl;
fut.wait();
doTheWork();
std::cout << "Work done." << std::endl;
}
void setDataReady(std::promise<void>&& prom){
std::cout << "Sender: Data is ready." << std::endl;
prom.set_value();
}
int main(){
std::cout << std::endl;
std::promise<void> sendReady;
auto fut = sendReady.get_future();
std::thread t1(waitingForWork, std::move(fut));
std::thread t2(setDataReady, std::move(sendReady));
t1.join();
t2.join();
Multithreading 156
std::cout << std::endl;
}