#include <iostream>
#include <thread>
#include <mutex>
// 定义一个互斥锁
std::mutex mtx;
void print_block(int n, char c) {
// 锁定互斥锁
mtx.lock();
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
// 解锁互斥锁
mtx.unlock();
}
int main() {
std::thread th1(print_block, 5, '*');
std::thread th2(print_block, 3, '$');
th1.join();
th2.join();
return 0;
}
<iostream>
, <thread>
, 和 <mutex>
分别用于输入输出、线程管理和互斥锁。std::mutex mtx;
创建了一个全局的互斥锁对象 mtx
,用于保护共享资源(在这里是标准输出)。print_block
:该函数接受两个参数,一个是打印字符的数量 n
,另一个是字符 c
。在打印字符之前,它会锁定互斥锁 (mtx.lock()
),以确保同一时间只有一个线程可以执行这段代码。打印完成后,解锁互斥锁 (mtx.unlock()
)。main
:创建了两个线程 th1
和 th2
,分别调用 print_block
函数。使用 join
确保主线程等待子线程完成。这样可以避免多个线程同时访问共享资源(如标准输出)时可能出现的竞争条件。
上一篇:c++面向过程还是面向对象
下一篇:c++编程教程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站