如何在 C++ 中的单独线程上 运行 method/function

How to run method/function on a separate thread in c++

我是c++初学者,所以了解的不多

这是一个函数

void example(){
     for(int i=0; i<5; i++){
          // do stuff
     }
}

如果我调用这个函数,它会等待它完成后再继续

int main(){
     example();

     otherThingsGoHere();
     otherThingsGoHere();
     otherThingsGoHere();

     return 0;
}

在 example() 完成之前不会调用 otherThingsGoHere()

我的目标是让该函数能够永远以 60/70 fps 的速度循环播放

我确实让它工作了,除了下面的任何事情都不会发生,因为它处于无限循环中。

我从事 C# 开发已有一段时间了,我知道在 C# 中,您可以在单独的线程上使用异步函数 运行。我如何在 C++ 中实现类似的东西?

编辑:我不是要你把 otherThingsGoHere 放在 main 前面,因为其他东西将是另一个循环,所以我需要它们同时 运行

您需要使用该新线程中的 std::thread 和 运行 example() 函数。

一个std::thread可以在构造函数到运行时启动。 它将 运行 可能与主线程 运行 并行 otherThingsGoHere。 我写的可能是因为它取决于您的系统和内核数量。如果您有一台多核 PC,它实际上可以 运行 那样。 在 main() 退出之前,它应该通过调用 thread::join().

等待另一个线程正常结束

您的情况的一个最小示例是:

#include <thread>
#include <iostream>

void example() {
    for (int i = 0; i<5; i++) {
        std::cout << "thread...\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

void otherThingsGoHere() {
    std::cout << "do other things ...\n";
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

int main() {
    std::thread t{ example };

    otherThingsGoHere();
    otherThingsGoHere();
    otherThingsGoHere();

    t.join();
    return 0;
}

这里有更多信息:Simple example of threading in C++