最近学习了一下C++11的新特性,发现c++的进步很快,已经不在是我最早认识的那个c++了。
我的感觉是c++的更新的三个方向:
一个是语法层面上的
语法层面上面应该是借鉴了像python语言这样的语法,比如for -each,auto 等这样的“语法糖”。STL / 第三方库 下面的更新
比如加入unorder_map / set 等
thread库,之前c++在window下和linux创建线程的api完全不一样,但是c++11之后,可以使用头文件thread,基本上统一了跨平台的问题。我觉得这个很好。c++核心的更新
比如加入智能指针,lambda函数,右值引用等
下面打算写的是 c++11 下面的线程库。基本上是参考cppreference : http://en.cppreference.com/w/cpp/thread/thread
还有一个不错的教程:
https://www.cnblogs.com/ittinybird/p/4820142.html
一个简单的例子(注意这段代码在window下也是可以运行的):
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
using namespace std;
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));
}
}
int main()
{
int n = 0;
std::thread t1(f1,n);
t1.join();
std::cout << "Final value of n is " << n << '\n';
system("pause");
return 0;
}
进阶版的例子
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));
}
}
int main()
{
//使用智能指针的写法
int n = 0;
auto res = make_shared<thread>(f1, n);
res->join();
system("pause");
return 0;
}
上面是关于thread的api,另外关于线程的 join 和 detach 的区别。
在启动了一个线程(创建了一个thread对象)之后,当这个线程结束的时候,我们如何去回收线程所使用的资源呢?
thread库给我们两种选择:1.加入式(join()) 2.分离式(detach())。join指的是主线程卡在join的地方,等待子线程执行完毕,然后回收他。detach指的子线程和主线程已经不再有任何交互了,各干各的事情。
线程同步的例子
- mutex
- 条件变量
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
using namespace std;
std::mutex mtx; // 全局互斥锁.
std::condition_variable cv; // 全局条件变量.
bool ready = false; // 全局标志位.
void do_print_id(int id)
{
std::unique_lock <std::mutex> lck(mtx);
cout << "-- test --" << endl;
while (!ready) // 如果标志位不为 true, 则等待...
cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,
// 线程被唤醒, 继续往下执行打印线程编号id.
std::cout << "thread " << id << '\n';
}
void go()
{
std::unique_lock <std::mutex> lck(mtx);
ready = true; // 设置全局标志位为 true.
cv.notify_all(); // 唤醒所有线程.
} // unique_lock 在自己的声明周期结束的时候 自动释放锁
int main()
{
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(do_print_id, i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto & th : threads)
th.join();
system("pause");
return 0;
}
other
c++11的线程封装的很好,用起来也很方便,而且还跨平台。
推荐一个github :
《C++ 并发编程指南》
https://github.com/forhappy/Cplusplus-Concurrency-In-Practice