C++中实现多线程的方法有多种,以下是其中一种常见的方法:

  1. 使用C++11标准的线程库
#include <iostream>
#include <thread>

void foo() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    // 创建一个线程并执行函数foo
    std::thread t(foo);

    // 等待线程执行完毕
    t.join();

    return 0;
}

在上面的例子中,我们使用std::thread类创建一个新的线程,并在其中执行函数foot.join()会等待线程执行完毕。

  1. 使用函数指针和函数对象
#include <iostream>
#include <thread>

void foo() {
    std::cout << "Hello from thread!" << std::endl;
}

class Bar {
public:
    void operator()() {
        std::cout << "Hello from thread!" << std::endl;
    }
};

int main() {
    // 使用函数指针创建线程
    std::thread t1(&foo);

    // 使用函数对象创建线程
    Bar bar;
    std::thread t2(bar);

    // 等待线程执行完毕
    t1.join();
    t2.join();

    return 0;
}

在上面的例子中,我们使用函数指针&foo和函数对象Bar创建了两个不同的线程。

  1. 使用Lambda表达式
#include <iostream>
#include <thread>

int main() {
    // 使用Lambda表达式创建线程
    std::thread t([]() {
        std::cout << "Hello from thread!" << std::endl;
    });

    // 等待线程执行完毕
    t.join();

    return 0;
}

在上面的例子中,我们直接将Lambda表达式作为线程的执行函数。

无论使用哪种方法,我们都需要使用std::thread类来创建和管理线程,并使用join()函数来等待线程执行完毕

c++实现多线程

原文地址: https://www.cveoy.top/t/topic/iyFf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录