C++11标准给了很多“终于等到了”的功能,其中一项就是线程类<thread> ,有朝一日终于可以减少操作系统相关了,隔壁J家笑而不语。
用法真是简单多了,最简单的一种如下:
#include <thread> #include <iostream> using namespace std; void pause_thread(int n) { this_thread::sleep_for(chrono::seconds(2)); cout << "thread of " << n << " ended\n"; } int main() { int N = 0; cin >> N; thread* ths = new thread[N]; for (int i = 0; i < N; i++) { ths[i] = thread(pause_thread, i); } cout << "Finished spawning threads." << endl; for (int i = 0; i < N; i++) { ths[i].join(); } cout << "All threads joined!" << endl; delete[]ths; return 0; }
上面程序的输出:
当然由于我的函数里定义的不是原子操作,所以cout的时候就混杂了~
所以可以用到<mutex> 类里面的互斥量来解决一下,比如这样
#include <thread> #include <mutex> #include <iostream> using namespace std; void pause_thread(int n, mutex* mtx) { this_thread::sleep_for(chrono::seconds(2)); (*mtx).lock(); cout << "thread of " << n << " ended\n"; (*mtx).unlock(); } int main() { int N = 0; cin >> N; thread* ths = new thread[N]; mutex mtx; for (int i = 0; i < N; i++) { ths[i] = thread(pause_thread, i, &mtx); } cout << "Finished spawning threads." << endl; for (int i = 0; i < N; i++) { ths[i].join(); } cout << "All threads joined!" << endl; delete[]ths; return 0; }
然后我们可以看到,输出不会绕在一起了~当然还是无序的,哈哈
查文档的时候注意到,竟然还有死锁检测相关的exception可能会抛出,有点良心的…这几天好好研究一下~