Knowledge Point 1
Reprinted from https://www.ev0l.art/index.php/archives/9/
- CPP Linux compiler with <thread> need to add -pthread compiler option. E.g:
g++ -std=c++11 -pthread a.cpp
- CPP QT Creator compiled with <thread> has BUG, they did not know how to remove!
Code 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; }
Knowledge Point 2
<Li> as an internal thread on to
Keyword | explain in detail |
---|---|
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) |
<Li> binding thread detach from the main thread, the main thread hung up, the child is not being given thread, the child thread executing the automatic exit.
After <li> thread detach, the child thread thread will become orphans, will not communicate between threads.
Knowledge Point 3
<Li> competition control variable thread is achieved by mutex automic
<Li> mutex: mutex. Need to include header <mutex> use -> Slow
<Li> atomic atomic variables. Need to include the header file <atomic> to achieve -> fast, thread-safe.
Code 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; }
Results not run 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 }
Operation result is 1000000 × 2. correct
<Li> Atomic declared way atomic <int> a (100) ; initialization error equals
<Li> Vim pressing CTRL + exit die away after pressing CTRL + S Q