thread
介绍
之前有讨论过 pthread 这个库,这个库是 POSIX 系统的标准库,而 thread 是 C++11 的标准库,因此在多数能编译 C++ 的平台上直接运行(需要系统的支持)。
示例
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int counter = 0;
void increaseCounterA(int& counter, std::mutex& mtx)
{
while(1)
{
std::chrono::seconds sleepTime(2);
std::this_thread::sleep_for(sleepTime);
mtx.lock();
++counter;
std::cout << "A Counter value: " << counter << std::endl;
mtx.unlock();
}
}
void increaseCounterB(int& counter, std::mutex& mtx)
{
while(1)
{
std::chrono::seconds sleepTime(2);
std::this_thread::sleep_for(sleepTime);
mtx.lock();
++counter;
std::cout << "B Counter value: " << counter << std::endl;
mtx.unlock();
}
}
int main()
{
std::thread t1{increaseCounterA, std::ref(counter), std::ref(mtx)};
std::thread t2{increaseCounterB, std::ref(counter), std::ref(mtx)};
t1.join();
t2.join();
return 0;
}
上面的示例展示了 thread 库的接口,可以观察到几点:
- 共享的资源通过线程的构造函数参数传入,线程回调函数通过引用接收;
- 锁也通过参数传入
有多把锁的时候使用 std::lock_guard 或者 std::unique_lock
unique_lock
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mutex;
void workerThread()
{
std::unique_lock<std::mutex> lock(mutex);
std::cout << "Worker thread is running." << std::endl;
lock.unlock();
}
int main()
{
std::thread worker(workerThread);
std::unique_lock<std::mutex> lock(mutex);
std::cout << "Main thread is running." << std::endl;
lock.unlock();
worker.join();
return 0;
}
条件变量
解决死锁问题的,同 pthread 笔记
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mutex;
std::condition_variable condVar;
bool ready = false;
void workerThread()
{
// 模拟一些耗时的操作
std::this_thread::sleep_for(std::chrono::seconds(1));
std::unique_lock<std::mutex> lock(mutex);
ready = true;
lock.unlock();
condVar.notify_one();
}
int main()
{
std::thread worker(workerThread);
std::unique_lock<std::mutex> lock(mutex);
while (!ready) {
condVar.wait(lock);
}
std::cout << "Worker thread is ready." << std::endl;
worker.join();
return 0;
}
这里是主线程先释放锁进行等待