C++11語言本身支持了多線程。在以往,linux和windows下創建線程的方式是不一樣的,這也就降低了程序的可移植性和可讀性。
以前對多前程的了解不多,最近在看一些C++11的新特性,看到多線程這里,故做以記錄。
創建線程的兩種方式:
1.線程的入口必須是一個函數,那么就可以用函數的方式:
1)導入線程庫函數:#include<Thread>
2)使用Thread mytobj(printf)創建一個線程。printf是函數名,也就是線程的入口地址
1 //自己創建的線程也要從一個函數開始執行 2 void mythread() { 3 cout << "這是我創建的線程1" << endl; 4 cout << "這是我創建的線程2" << endl; 5 cout << "這是我創建的線程3" << endl; 6 cout << "這是我創建的線程4" << endl; 7 cout << "這是我創建的線程5" << endl; 8 cout << "這是我創建的線程6" << endl; 9 cout << "這是我創建的線程7" << endl; 10 cout << "這是我創建的線程8" << endl; 11 cout << "這是我創建的線程9" << endl; 12 } 13 int main() //主線程 14 { 15 //創建一個線程 16 thread mytobj(mythread); 17 if (mytobj.joinable()) 18 { 19 cout << "現在可以detach或者join:1" << endl; 20 } 21 else 22 { 23 cout << "現在不能detach或者join:1" << endl; 24 } 25 mytobj.join(); 26 //mytobj.detach(); 27 if (mytobj.joinable()) 28 { 29 cout << "現在可以detach或者join:2" << endl; 30 } 31 else 32 { 33 cout << "現在不能detach或者join:2" << endl; 34 } 35 }
2.使用類對象來創建線程
1 //使用類對象來創建線程 2 int data = 10; 3 char a = 'a'; 4 char *p = &a; 5 std::string str = "you are pretty good!!!!!!!!!!!!!!!"; 6 CreatThreadClass ctc(data,p); 7 thread mytobj(ctc); 8 if (mytobj.joinable()) 9 { 10 cout << "現在可以創建一個線程1" << endl; 11 } 12 else 13 { 14 cout << "現在不能創建一個線程1" << endl; 15 } 16 mytobj.detach(); 17 18 if (mytobj.joinable()) 19 { 20 cout << "現在可以創建一個線程2" << endl; 21 } 22 else 23 { 24 cout << "現在不能創建一個線程2" << endl; 25 } 26 std::string str222 = GetIns::getinstance()->lastFunc(str); 27 cout << str222 << endl; 28 }
使用類對象來創建線程,必要要重載()運算符,在這個重載函數中,調用其他的函數。
1 void operator()(){ 2 3 //TODO 4 }