以下是一个简单的多线程程序应用,使用 C++ 编写,包含一个 Main 类、Lefthand 类和 Righthand 类,实现 Lefthand 类打印 10 次'我是左手',Righthand 类打印 5 次'我是右手'的功能:

#include <iostream>
#include <thread>

class Lefthand {
public:
    void printMessage() {
        for (int i = 0; i < 10; ++i) {
            std::cout << '我是左手' << std::endl;
        }
    }
};

class Righthand {
public:
    void printMessage() {
        for (int i = 0; i < 5; ++i) {
            std::cout << '我是右手' << std::endl;
        }
    }
};

int main() {
    Lefthand lefthand;
    Righthand righthand;

    std::thread thread1(&Lefthand::printMessage, &lefthand);
    std::thread thread2(&Righthand::printMessage, &righthand);

    thread1.join();
    thread2.join();

    return 0;
}

在程序中,我们定义了 Lefthand 类和 Righthand 类,分别表示左手和右手。它们都有一个 printMessage 方法,用于打印相应的消息。在 Main 类中,我们创建了一个 Lefthand 对象和一个 Righthand 对象。然后,使用 std::thread 创建了两个线程,并将 printMessage 方法与相应的对象进行绑定。最后,使用 join 函数等待两个线程执行完成。

当程序运行时,Lefthand 类将打印 10 次'我是左手',而 Righthand 类将打印 5 次'我是右手'。请注意,由于多线程的执行顺序是不确定的,因此打印结果可能会有所不同。

C++ 多线程程序示例:左手和右手打印

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

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