共享内存 同一时刻只允许一个线程使用,要对访问临界资源的代码加锁保护。该程序中三个线程中var 的访问需加锁保护,保证了三个线程不会同时对 var 进行处理。
#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
#include <thread>
double var = 100;
std::mutex mymutex;
void Threadwirte()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(1., 1024.);
for (size_t i = 0; i < 100; ++i)
{
double random_data= dis(gen);
{
std::lock_guard<std::mutex> lg(mymutex);
var = random_data;
std::cout << "thread Write:" << var << std::endl << std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void Threadread1()
{
for (size_t i = 0; i < 10; ++i)
{
{