#include <iostream>
#include <ctime>
#include <mutex>
#include <vector>
#include <thread>
#include <atomic>
std::mutex mtx;
size_t count = 0;
//使用atomic
std::atomic<size_t> count_1(0);
void threadFun()
{
for (int i = 0; i < 10000; i++)
{
// 防止多个线程同时访问同一资源
std::unique_lock<std::mutex> lock(mtx);
count++;
}
}
void threadFun1()
{
for (int i = 0; i < 10000; i++)
count_1++;
}
int main()
{
clock_t start_time = clock();
// 启动多个线程
std::vector<std::thread> threads;
for (int i = 0; i < 10; i++)
threads.push_back(std::thread(threadFun1));
for (auto& thad : threads)
thad.join();
// 检测count是否正确 10000*10 = 100000
std::cout << "count number:" << count + int(count_1) << std::endl;
clock_t end_time = clock();
std::cout << "耗时:" << end_time - start_time << "ms" << std::endl;
return 0;
}
参考:::https://blog.csdn.net/qq_34199383/article/details/79990986?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control