#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
// 互斥锁,用于保护共享资源
std::mutex mtx;
void print_block(int n, int id) {
// 锁定互斥锁,确保同一时间只有一个线程可以访问临界区
std::lock_guard<std::mutex> lock(mtx);
for (int i = 0; i < n; ++i) {
std::cout << "Thread " << id << ": " << i << std::endl;
}
}
int main() {
const int N = 10;
std::vector<std::thread> threads;
// 创建多个线程并启动它们
for (int i = 0; i < 5; ++i) {
threads.push_back(std::thread(print_block, N, i));
}
// 等待所有线程完成
for (auto& th : threads) {
th.join();
}
return 0;
}
这段代码展示了如何使用 C++ 进行简单的并行编程。具体来说:
引入必要的头文件:
#include <iostream>:用于标准输入输出。#include <vector>:用于创建动态数组。#include <thread>:用于创建和管理线程。#include <mutex>:用于线程同步。定义互斥锁:
std::mutex mtx:互斥锁用于保护共享资源(如标准输出),防止多个线程同时访问导致数据竞争。定义线程函数:
void print_block(int n, int id):每个线程执行的函数,打印指定数量的数字,并标明是哪个线程在打印。std::lock_guard<std::mutex> 自动管理互斥锁的锁定和解锁,确保临界区的安全。主函数:
threads。print_block 函数,传递参数 N 和线程 ID。join() 等待所有线程完成。通过这种方式,多个线程可以并发执行任务,而互斥锁确保了对共享资源的安全访问。
上一篇:c++取随机数
下一篇:c++数组去重方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站