C++創(chuàng)建線程的三種方式
早期的C++并不支持多線程的創(chuàng)建,如果要創(chuàng)建多線程,依賴的是系統(tǒng)提供的一些方法(例如linux的 pthread). 從C++11以后開始,提供了std::thread線程庫,因此我們可以創(chuàng)建std::thread類對象的方式來創(chuàng)建線程。創(chuàng)建的方式主要有三種:
創(chuàng)建線程的三種方式:
- 通過函數(shù)指針
- 通過函數(shù)對象
- 通過lambda函數(shù)
使用std::thread類創(chuàng)建對象,必須包含頭文件
#include <thread>
創(chuàng)建的形式是
std::thread thobj(<CALL_BACK>)
新線程將在創(chuàng)建新對象后立即啟動,并將與啟動該線程的線程并行執(zhí)行傳遞的回調。而且,任何線程都可以通過在該線程的對象上調用join()函數(shù)來等待另一個線程退出。
通過函數(shù)指針創(chuàng)建線程
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void thread_func()
{
for(int i= 0; i< 10; ++i)
{
cout<<" thread thread_func is running..."<< endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
thread threadobj(thread_func);
cout<<"main Thread is running..."<<endl;
threadobj.join();
cout<<" exit from main Thread"<<endl;
return 0;
}
需要注意的是, thread threadobj(thread_func), 函數(shù)名是不加括號的。文章來源:http://www.zghlxwxcb.cn/news/detail-589229.html
通過函數(shù)對象創(chuàng)建線程
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
class Thread_Test
{
public:
void operator()()
{
for(int i = 0; i < 10; i++)
{
cout<<" Thread_Test is running..."<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
};
int main()
{
thread threadobj((Thread_Test()));
cout<<"main Thread is running..."<<endl;
threadobj.join();
cout<<" exit from main Thread"<<endl;
return 0;
}
與上面的方法對比,此處對象Thread_Test()是必須要加括號的.關于operator() 函數(shù)對象(仿函數(shù))的相關知識不在這里展開。文章來源地址http://www.zghlxwxcb.cn/news/detail-589229.html
lambda函數(shù)創(chuàng)建線程
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
cout<<"main Thread is running..."<<endl;
thread threadobj([]{
for (int i = 0; i < 10; i++)
{
cout<<"lambda thread is running ..." <<endl;
::this_thread::sleep_for(::chrono::seconds(1));
}
});
threadobj.join();
cout<<" exit from main Thread"<<endl;
return 0;
}
到了這里,關于C++創(chuàng)建線程的三種方式的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!