C++多執行緒初級一:建立執行緒
阿新 • • 發佈:2019-01-26
以函式為引數建立執行緒:
// PolythreadDemo.cpp : 定義控制檯應用程式的入口點。 //這裡有一個觀點,就是當使用某個函式的時候,再 //寫上標頭檔案,不用一開始就來、 #include "stdafx.h" #include <iostream> #include <thread> #include <windows.h> using namespace std; void hello(){ cout << "Hollo,Nima World!" << endl; } int _tmain(int argc, _TCHAR* argv[]) { std::thread t(hello); t.join(); //只有上面兩句話,和之前的預處理指令 Sleep(3000); //定義在windows.h裡面、 return 0; }
以函式物件為引數建立執行緒
// PolythreadDemo.cpp : 定義控制檯應用程式的入口點。 //這裡有一個觀點,就是當使用某個函式的時候,再 //寫上標頭檔案,不用一開始就來、 #include "stdafx.h" #include <iostream> #include <thread> #include <windows.h> using namespace std; void hello(){ cout << "Hollo,Nima World!" << endl; } class Hello { public: Hello(){} //建構函式、 void operator()()const { std::cout << "Hello,World!" << std::endl; } }; int _tmain(int argc, _TCHAR* argv[]) { Hello h; std::thread t1((h)); //原文中只有一個括號,沒看懂,放兩個括號就清楚了 t1.join(); //只有上面兩句話,和之前的預處理指令 Sleep(3000); //定義在windows.h裡面、 return 0; }
以類方法作為引數建立執行緒:
// PolythreadDemo.cpp : 定義控制檯應用程式的入口點。 //這裡有一個觀點,就是當使用某個函式的時候,再 //寫上標頭檔案,不用一開始就來、 #include "stdafx.h" #include <iostream> #include <thread> #include <windows.h> #include <string> using namespace std; void hello(){ cout << "Hollo,Nima World!" << endl; } class Hello { public: Hello(){} //建構函式、 //注意函式名必須唯一才能做多執行緒、 void hello1(){ cout << "Hollo,Nima World!" << endl; } void hello2(std::string text){ //string 要加String標頭檔案 cout << "Hollo,Nima World!" << text << endl; } }; int _tmain(int argc, _TCHAR* argv[]) { Hello h; std::thread t1(&Hello::hello1,&h); std::thread t2(&Hello::hello2,&h,"Shawn"); t1.join(); t2.join(); Sleep(3000); //定義在windows.h裡面、 return 0; }
以lambda物件作為引數建立執行緒
// PolythreadDemo.cpp : 定義控制檯應用程式的入口點。
//這裡有一個觀點,就是當使用某個函式的時候,再
//寫上標頭檔案,不用一開始就來、
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <windows.h>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
std::thread t([](std::string text){
std::cout << "Hello,caodan World!" << text << std::endl;
}, "Shawn");
t.join();
Sleep(3000); //定義在windows.h裡面、
return 0;
}