C++ 多线程编程示例:使用互斥锁实现同步打印
C++ 多线程编程示例:使用互斥锁实现同步打印
以下是用 C++ 实现上述任务的示例代码:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
class Lefthand {
public:
void printMessage() {
for (int i = 0; i < 10; i++) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << '我是左手' << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
};
class Righthand {
public:
void printMessage() {
for (int i = 0; i < 5; i++) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << '我是右手' << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
};
int main() {
Lefthand lefthand;
Righthand righthand;
std::thread thread1(&Lefthand::printMessage, &lefthand);
std::thread thread2(&Righthand::printMessage, &righthand);
thread1.join();
thread2.join();
return 0;
}
在这个示例中,我们使用了 C++ 的标准库中的 <iostream>、<thread> 和 <mutex> 头文件。
在 Lefthand 类中,我们使用 std::mutex 来实现互斥锁,保证多个线程之间的打印操作是同步的。std::lock_guard 用于自动获取和释放互斥锁,确保在每次打印消息时只有一个线程访问资源。
在 Righthand 类中,同样使用互斥锁来保证线程安全。
在 main() 函数中,我们创建了 Lefthand 对象和 Righthand 对象,并使用 std::thread 创建了两个线程,分别执行 printMessage() 方法。使用 std::thread 创建并启动线程。
使用 join() 函数等待两个线程执行完成。
运行程序后,Lefthand 类将打印 10 次“我是左手”,而 Righthand 类将打印 5 次“我是右手”。由于多线程的执行顺序是不确定的,因此打印结果可能会有所不同。确保编译器支持 C++11 及以上版本来使用多线程库。
原文地址: http://www.cveoy.top/t/topic/DR3 著作权归作者所有。请勿转载和采集!