問題描述
有人可以發(fā)布一個(gè)在 C++ 中啟動兩個(gè)(面向?qū)ο?線程的簡單示例.
Can someone post a simple example of starting two (Object Oriented) threads in C++.
我正在尋找可以擴(kuò)展運(yùn)行方法(或類似的東西)而不是調(diào)用 C 樣式線程庫的實(shí)際 C++ 線程對象.
I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.
我省略了任何特定于操作系統(tǒng)的請求,希望回復(fù)的人會回復(fù)要使用的跨平臺庫.我現(xiàn)在只是明確說明這一點(diǎn).
I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.
推薦答案
創(chuàng)建一個(gè)你想讓線程執(zhí)行的函數(shù),例如:
Create a function that you want the thread to execute, eg:
void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}
現(xiàn)在創(chuàng)建 thread
對象,它最終會像這樣調(diào)用上面的函數(shù):
Now create the thread
object that will ultimately invoke the function above like so:
std::thread t1(task1, "Hello");
(您需要#include
才能訪問std::thread
類)
(You need to #include <thread>
to access the std::thread
class)
構(gòu)造函數(shù)的參數(shù)是線程將執(zhí)行的函數(shù),后跟函數(shù)的參數(shù).線程在構(gòu)建時(shí)自動啟動.
The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
如果稍后您想等待線程完成執(zhí)行函數(shù),請調(diào)用:
If later on you want to wait for the thread to be done executing the function, call:
t1.join();
(加入意味著調(diào)用新線程的線程將等待新線程執(zhí)行完畢,然后它才會繼續(xù)自己的執(zhí)行).
(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
這里有關(guān)于 std::thread 的更多信息
- 在 GCC 上,使用
-std=c++0x -pthread
編譯. - 這應(yīng)該適用于任何操作系統(tǒng),前提是您的編譯器支持此 (C++11) 功能.
這篇關(guān)于C++ 中線程的簡單示例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!