C++ 中线程的简单示例

Simple example of threading in C++(C++ 中线程的简单示例)
本文介绍了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) 功能.

这篇关于C++ 中线程的简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)