#c++11 多线程
引入多线程,对于跨平台开发提供了很大的便捷
mutex lock
int g_i = 0;
std::mutex mm;
void add_one()
{
for (size_t i = 0; i < 10; i++)
{
std::unique_lock<std::mutex> lck(mm);//默认创建时加锁
//do something with g_i++
lck.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
lck.lock();
g_i ++ ;
std::cout << g_i << " " << std::this_thread::get_id() << std::endl;
lck.unlock();
}
}
void lock_test()
{
std::vector<std::thread> ver;
int num = 0;
for (auto i = 0; i < 5; ++i) {
ver.emplace_back(add_one);
}
for (auto &t : ver) {
t.join();
}
}
mutex 种类
- std::mutex:最基本的mutex类。
- std::recursive_mutex:递归mutex类,能多次锁定而不死锁。
- std::time_mutex:定时mutex类,可以锁定一定的时间。
- std::recursive_timed_mutex:定时递归mutex类。
另外,还提供了两种锁类型:
- std::lock_guard:方便线程对互斥量上锁。
- std::unique_lock:方便线程对互斥量上锁,但提供了更好的上锁和解锁控制。
add_one 中锁的位置不同,打印输出不同。锁的范围若加在整个for 里,输出回等到当前线程输出完后接着下个线程输出,不会多个线程轮换输出。
condition_variable
std::condition_variable cv;
std::mutex cv_m; // This mutex is used for three purposes:
// 1) to synchronize accesses to i
// 2) to synchronize accesses to std::cerr
// 3) for the condition variable cv
int i = 0;
void waits()
{
std::unique_lock<std::mutex> lk(cv_m);
std::cerr << "Waiting... \n";
cv.wait(lk, [] {return i == 1; });
std::cerr << "...finished waiting. i == 1\n";
}
void signals()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lk(cv_m);
std::cerr << "Notifying...\n";
}
cv.notify_all();
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lk(cv_m);
i = 1;
std::cerr << "Notifying again...\n";
}
cv.notify_all();
}
void test_condiction()
{
std::thread t1(waits), t2(waits), t3(waits), t4(signals);
t1.join();
t2.join();
t3.join();
t4.join();
}
condition 用于线程间同步,这里wait 第二个参数lamda 表达式,只有表达式返回true,且被 notify时被唤醒。 目的是防止spurious wakeup,在POSIX Threads中多核系统中 条件竞争导致了虚假唤醒的发生
using namespace std::chrono_literals;
std::condition_variable wt_cv;
std::mutex wt_cv_m;
int wt_i = 0;
void wait_for(int idx)
{
std::unique_lock<std::mutex> lk(wt_cv_m);
if (wt_cv.wait_for(lk, idx * 100ms, [] {return wt_i == 1; }))
std::cerr << "Thread " << idx << " finished waiting. wt_i == " << wt_i << '\n';
else
std::cerr << "Thread " << idx << " timed out. wt_i == " << wt_i << '\n';
}
void waitfor_signals()
{
std::this_thread::sleep_for(120ms);
std::cerr << "Notifying...\n";
wt_cv.notify_all();
std::this_thread::sleep_for(100ms);
{
std::lock_guard<std::mutex> lk(wt_cv_m);
wt_i = 1;
}
std::cerr << "Notifying again...\n";
wt_cv.notify_all();
}
void test_wait_for()
{
std::thread t1(wait_for, 1), t2(wait_for, 2), t3(wait_for, 3), t4(waitfor_signals);
t1.join();
t2.join();
t3.join();
t4.join();
}
wait_for 还能加个超时等待时间来控制,这个功能强大,可以用来实现定时器。
atomic
当多线程访问共享资源时,atomic 类型编译器能保证对其操作是原子操作, 而且提供比mutex等锁机制更好的性能,
reference: https://blog.csdn.net/yockie/article/details/8838686