C++11 多线程相关的头文件
C++11 新标准中引入了五个头文件来支持多线程编程,他们分别是<atomic> ,<thread>,<mutex>,<condition_variable>和<future>。
- <atomic>:该头文主要声明了两个类, std::atomic 和 std::atomic_flag,另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。
- <thread>:该头文件主要声明了 std::thread 类,另外 std::this_thread 命名空间也在该头文件中。
- <mutex>:该头文件主要声明了与互斥量(mutex)相关的类,包括 std::mutex 系列类,std::lock_guard, std::unique_lock, 以及其他的类型和函数。
- <condition_variable>:该头文件主要声明了与条件变量相关的类,包括 std::condition_variable 和 std::condition_variable_any。
- <future>:该头文件主要声明了 std::promise, std::package_task 两个 Provider 类,以及 std::future 和 std::shared_future 两个 Future 类,另外还有一些与之相关的类型和函数,std::async() 函数就声明在此头文件中。
thread
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread " << n << " executing\n";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int& n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
int n = 0;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + 1); // pass by value
std::thread t3(f2, std::ref(n)); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
t2.join();
t4.join();
std::cout << "Final value of n is " << n << '\n';
}
mutex
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
volatile int counter(0); // non-atomic counter
std::mutex mtx; // locks access to counter
void attempt_10k_increases() {
for (int i=0; i<10000; ++i) {
if (mtx.lock()) { // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
}
int main (int argc, const char* argv[]) {
std::thread threads[10];
for (int i=0; i<10; ++i)
threads[i] = std::thread(attempt_10k_increases);
for (auto& th : threads) th.join();
std::cout << counter << " successful increases of the counter.\n";
return 0;
}
condition_variable
创建ThreadA和ThreadB两个线程,线程分别运行的是A和B两个函数,线程ThreadB通过cv.wait()来阻塞等待,线程ThreadA通过修改全局标志位和cv.notify_one()来唤醒ThreadB继续往下运行。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mx; //全局互斥锁
condition_variable cv; //全局条件变量
bool ready = false; //全局标志位
void B(){
cout << "B begin\n" << endl;
unique_lock<mutex> lock(mx);
cout << "B wait\n" << endl;
while(!ready) //如果标志位不为 true, 则等待...
{
cv.wait(lock); //前线程被阻塞, 当全局标志位变为 true 之后,线程被唤醒, 继续往下执行
}
cout << "B wakeup\n" << endl;
}
void A(){
cout << "A begin\n" << endl;
this_thread::sleep_for(std::chrono::milliseconds(1000));
cout << "A notify B\n" << endl;
ready = true; // 设置全局标志位为 true
cv.notify_one(); // 唤醒上面的线程
}
int main()
{
thread ThreadB(B);
thread ThreadA(A);
ThreadB.join();
ThreadA.join();
cout << "over" << endl;
}