CPP 学习笔记-多线程

知识点1

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

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

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

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

代码1

#include v
#include 

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"<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)

    CPP 学习笔记-多线程_第1张图片

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

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

    知识点3

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

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

  • atomic 原子变量。需要包含头文件来实现 -->速度快,线程安全。

    代码3

    #include 
    #include 
    #include 
    #include 
    
    using namespace std; int count(0); void run() { for(int i(0);i<1000000;i++) { count++; cout<<"\t"<"\t"<"\t"; } } int main() { auto n=thread::hardware_concurrency(); thread* pt[n]; for(int z=0;z) { pt[z]=new thread(run); pt[z]->detach(); } cout<<"Finally count is \t"<endl; cout<<"Used "<"threads"<<endl; cin.get(); return 0; }

     

     

    运行结果不是1000000×2.

     1 #include 
     2 #include 
     3 #include 
     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"<"\t"<"\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) 23  { 24 pt[z]=new thread(run); 25 pt[z]->detach(); 26 27  } 28 29 cout<<"Finally count is \t"<endl; 30 cout<<"Used "<"threads"<<endl; 31 32 33 34 35 cin.get(); 36 return 0; 37 }

     

     

    运行结果是1000000×2.正确

  • atomic 声明方式为 atomic a(100); 等号初始化会报错

  • vim 按CTRL+S 后假死按 CTRL+q 退出

  • 你可能感兴趣的:(CPP 学习笔记-多线程)