CPP 学习笔记-多线程

知识点1

转载自 https://www.ev0l.art/index.php/archives/9/

- Linux 下编译 带<thread> 的CPP需要加上 -pthread 编译选项。例如:

g++ -std=c++11 -pthread a.cpp

- QT Creator 编译带<thread>的CPP有BUG,暂时不知道怎么去除!

代码1

#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

<li> 关于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)

1.jpeg

<li> 线程 detach 脱离主线程的绑定,主线程挂了,子线程不报错,子线程执行完自动退出。

<li> 线程 detach以后,子线程会成为孤儿线程,线程之间将无法通信。

知识点3

<li>线程中变量的竞争控制是通过 mutex automic 来实现的

<li>mutex : 互斥量。需要包含头文件 <mutex> 来使用 -->速度慢

<li>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.

 1 #include <stdlib.h>
 2 #include <thread>
 3 #include <atomic>
 4 
 5 using namespace std;  6 int count(0);  7  8 void run()  9 { 10 for(int i(0);i<1000000;i++) 11  { 12 count++; 13 cout<<"\t"<<i<<"\t"<<count<<"\t"; 14  } 15 } 16 17 int main() 18 { 19 auto n=thread::hardware_concurrency(); 20 21 thread* pt[n]; 22 for(int z=0;z<n;z++) 23  { 24 pt[z]=new thread(run); 25 pt[z]->detach(); 26 27  } 28 29 cout<<"Finally count is \t"<<count<<endl; 30 cout<<"Used "<<n <<"threads"<<endl; 31 32 33 34 35 cin.get(); 36 return 0; 37 }
 

运行结果是1000000×2.正确

<li>atomic 声明方式为 atomic<int> a(100); 等号初始化会报错

<li>vim 按CTRL+S 后假死按 CTRL+q 退出

猜你喜欢

转载自www.cnblogs.com/dev995/p/12132726.html
cpp