C++ 中线程的简单示例
有人可以发布一个在 C++ 中启动两个(面向对象)线程的简单示例.
Can someone post a simple example of starting two (Object Oriented) threads in C++.
我正在寻找可以扩展运行方法(或类似的东西)而不是调用 C 样式线程库的实际 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.
我省略了任何特定于操作系统的请求,希望回复的人会回复要使用的跨平台库.我现在只是明确说明这一点.
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.
推荐答案
创建一个你想让线程执行的函数,例如:
Create a function that you want the thread to execute, eg:
void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}
现在创建 thread
对象,它最终会像这样调用上面的函数:
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)
构造函数的参数是线程将执行的函数,后跟函数的参数.线程在构建时自动启动.
The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
如果稍后您想等待线程完成执行函数,请调用:
If later on you want to wait for the thread to be done executing the function, call:
t1.join();
(加入意味着调用新线程的线程将等待新线程执行完毕,然后它才会继续自己的执行).
(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();
}
这里有关于 std::thread 的更多信息
- 在 GCC 上,使用
-std=c++0x -pthread
编译. - 这应该适用于任何操作系统,前提是您的编译器支持此 (C++11) 功能.
相关文章