📜  c++ 将函数放在另一个线程中 - C++ (1)

📅  最后修改于: 2023-12-03 15:14:00.049000             🧑  作者: Mango

C++将函数放在另一个线程中

在C ++中,可以使用线程来并发执行代码。使用线程可以避免阻塞主线程,并使用系统资源来加速计算密集型操作。在本文中,我们将讨论如何将函数放在另一个线程中。

使用std::thread(C++11及更高版本)

C ++11及更高版本提供了std :: thread,它是一个轻量级的线程类,可以用于创建并发执行代码的线程对象。下面是将函数放在另一个线程中的示例:

#include <thread>
#include <iostream>

void foo()
{
    // some task
}

int main()
{
    std::thread t(foo); // create a thread and execute foo() in it
    t.join(); // join the thread with the main thread

    return 0;
}

在上述代码中,我们使用std :: thread创建了一个名为t的线程,并使用它来执行foo函数。我们使用t.join()将线程与主线程联系起来,以确保在主线程退出之前线程已经完成。如果未使用join()或detach()来处理线程,则在主线程退出时会调用std :: terminate程序退出处理程序。

使用Lambda表达式(C++11及更高版本)

还可以使用Lambda表达式将函数作为参数传递给线程构造函数。下面是使用Lambda表达式将函数放在另一个线程中的示例:

#include <thread>
#include <iostream>

int main()
{
    std::thread t([](){
        // some task
    }); // create a thread and execute a lambda function in it
    t.join(); // join the thread with the main thread

    return 0;
}

在上面的代码中,我们创建了一个没有名称的Lambda函数,并将其作为参数传递给std :: thread构造函数。通过这种方式,我们可以将任何代码放入线程中,而不必创建一个独立的函数。

使用std::async(C++11及更高版本)

C++11及更高版本还引入了std :: async函数,该函数在后台启动一个异步任务,并返回一个std :: future对象,该对象可以用于检索任务的结果。下面是使用std :: async启动异步任务的示例:

#include <future>
#include <iostream>

double foo(double val)
{
    // some long task ...
    return val * 2;
}

int main()
{
    std::future<double> f = std::async(std::launch::async, foo, 2.0); // start the async task and pass function and arguments
    std::cout << "result: " << f.get() << std::endl; // retrieve the result from the future object

    return 0;
}

在上述代码中,我们调用std :: async并传递三个参数:std :: launch :: async,foo函数和2.0作为函数的参数。这将在后台启动异步任务,并返回一个std :: future对象。请注意,第一个参数指定启动策略,std :: async可以使用三种不同方式启动异步任务:std :: launch :: async,std :: launch :: deferred和std :: launch :: any。在我们的示例中,我们使用了std :: launch :: async,这意味着我们将始终在后台启动异步任务。

使用f.get()获取异步任务的结果。此函数在等待异步任务完成后返回其结果。如果未完成,则get函数将阻塞调用线程,直到异步任务完成。

使用Boost.Thread

如果您在使用C ++03(或更低版本)或无法使用C ++11或更高版本,则可以使用Boost.Thread,它是一个免费和开源的C ++库,提供了线程支持。您可以使用它创建和管理线程,以及在不同的线程之间共享数据。以下是一个使用Boost.Thread创建线程的示例:

#include <boost/thread.hpp>
#include <iostream>

void foo()
{
    // some task ...
}

int main()
{
    boost::thread t(&foo); // create a thread and execute foo() in it
    t.join(); // join the thread with the main thread

    return 0;
}

在上面的代码中,我们使用boost :: thread创建一个名为t的线程,并使用它来执行foo函数。我们使用t.join()将线程与主线程联系起来,以确保在主线程退出之前线程已经完成。

结论

这是如何将函数放在另一个线程中。使用线程并行执行代码可以加快应用程序的速度并提高性能。请谨慎使用线程,因为使用它们时可能会出现问题,例如竞争条件和死锁。