C中线程的简单示例

新手上路,请多包涵

有人可以发布一个在 C++ 中启动两个(面向对象)线程的简单示例。

我正在寻找实际的 C++ 线程对象,我可以在其上扩展运行方法(或类似的东西),而不是调用 C 风格的线程库。

我省略了任何特定于操作系统的请求,希望回复的人会回复跨平台库以供使用。我现在只是明确表示。

原文由 Zak 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 543
2 个回答

创建一个您希望线程执行的函数,例如:

 void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

现在创建 thread 对象,该对象最终将调用上述函数,如下所示:

 std::thread t1(task1, "Hello");

(您需要 #include <thread> 才能访问 std::thread 类。)

构造函数的第一个参数是线程将执行的函数,然后是函数的参数。线程在构造时自动启动。

如果稍后您想等待线程完成执行该函数,请调用:

 t1.join();

(加入意味着调用新线程的线程将等待新线程完成执行,然后再继续自己的执行。)


编码

#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 ) 功能。

原文由 MasterMastic 发布,翻译遵循 CC BY-SA 4.0 许可协议

#include <thread>
#include <iostream>
#include <vector>
using namespace std;

void doSomething(int id) {
    cout << id << "\n";
}

/**
 * Spawns n threads
 */
void spawnThreads(int n)
{
    std::vector<thread> threads(n);
    // spawn n threads:
    for (int i = 0; i < n; i++) {
        threads[i] = thread(doSomething, i + 1);
    }

    for (auto& th : threads) {
        th.join();
    }
}

int main()
{
    spawnThreads(10);
}

原文由 Caner 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题