知识点1
- Linux 下编译 带<thread> 的CPP需要加上 -pthread 编译选项。例如: ``` g++ -std=c++11 -pthread a.cpp
<li>QT Creator 编译带<thread>的CPP有BUG,暂时不知道怎么去除! #### 代码1 ```#include <iostream> #include <stdlib.h>v #include <thread> using namespace std; void run(char* p) { int i=0; i=system(p); } int main() { char p[5][20]={ "ls", "echo nihao", "gnome-terminal", "terminator", "ps -aux" }; while("nimei") { static int i(0); if(i<5){ thread *pt=new thread(run,p[i]); i+=1; cout<<"I now is :\t"<<i<<endl; } else{ break; } cout<<"Breaking...."<<endl; } cin.get(); return 0; }
知识点2
- 关于thread类的内部成
关键字 详细解释 id Thread的id native_handle_type native_handle_type operator= Move massive Thread get_id get Thread ID joinable get if joinable join join thread detach detach thread swap swap thread native_handle get native handle hardware_concurrency[static] Detect hardware concurrency (public static function) - 线程 detach 脱离主线程的绑定,主线程挂了,子线程不报错,子线程执行完自动退出。
- 线程 detach以后,子线程会成为孤儿线程,线程之间将无法通信。
知识点3
- 线程中变量的竞争控制是通过 mutex automic 来实现的
- mutex : 互斥量。需要包含头文件 <mutex> 来使用 -->速度慢
- atomic 原子变量。需要包含头文件<atomic>来实现 -->速度快,线程安全。
代码3
#include <iostream> #include <stdlib.h> #include <thread> #include <atomic> using namespace std; int count(0); void run() { for(int i(0);i<1000000;i++) { count++; cout<<"\t"<<i<<"\t"<<count<<"\t"; } } int main() { auto n=thread::hardware_concurrency(); thread* pt[n]; for(int z=0;z<n;z++) { pt[z]=new thread(run); pt[z]->detach(); } cout<<"Finally count is \t"<<count<<endl; cout<<"Used "<<n <<"threads"<<endl; cin.get(); return 0; }
运行结果不是1000000×2.
#include <stdlib.h> #include <thread> #include <atomic> using namespace std; int count(0); void run() { for(int i(0);i<1000000;i++) { count++; cout<<"\t"<<i<<"\t"<<count<<"\t"; } } int main() { auto n=thread::hardware_concurrency(); thread* pt[n]; for(int z=0;z<n;z++) { pt[z]=new thread(run); pt[z]->detach(); } cout<<"Finally count is \t"<<count<<endl; cout<<"Used "<<n <<"threads"<<endl; cin.get(); return 0; }
运行结果是1000000×2.正确
- atomic 声明方式为 atomic<int> a(100); 等号初始化会报错
- vim 按CTRL+S 后假死按 CTRL+q 退出