64,637
社区成员
发帖
与我相关
我的任务
分享
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#define THREAD_COUNT_FOR_TEST 10
using namespace std;
int volatile g_mems[THREAD_COUNT_FOR_TEST]; //简化一下, 用mems[0]~~mems[THREAD_COUNT_FOR_TEST-1]用这个来代表10个不同内存区域
bool volatile g_memsLockFlag[THREAD_COUNT_FOR_TEST];//标记内存是否已被占
std::mutex gl_mutex;
std::condition_variable g_cv;
void readTread(int memIdx, int randSeed)
{
srand(randSeed);
//本代码中所有sleep都是为了模拟线程卡顿,验证互斥保护的效果
int sleepTime = rand() % 1500 ;
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
printf("read thread, idx(%d), after %d ms sleep, begin to work!\n", memIdx, sleepTime);
{
std::unique_lock<std::mutex> lock(gl_mutex);
g_cv.wait(lock, [memIdx](){return !g_memsLockFlag[memIdx]; });
g_memsLockFlag[memIdx] = true;
}
//模拟读数据,这里是简单打印
printf("read thread, idx(%d), get value:%d!\n", memIdx, g_mems[memIdx]);
{
std::unique_lock<std::mutex> lock(gl_mutex);
g_memsLockFlag[memIdx] = false;
}
printf("read thread, idx(%d), finished work and unlock source!\n", memIdx);
g_cv.notify_all();
}
void wirteTread(int memIdx, int randSeed)
{
srand(randSeed);
//本代码中所有sleep都是为了模拟线程卡顿,验证互斥保护的效果
int sleepTime = rand() % 1500;
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
printf("write thread, idx(%d), after %d ms sleep, begin to work!\n", memIdx, sleepTime);
{
std::unique_lock<std::mutex> lock(gl_mutex);
g_cv.wait(lock, [memIdx](){return !g_memsLockFlag[memIdx]; });
g_memsLockFlag[memIdx] = true;
}
int newValue =1 + rand() % 100;
g_mems[memIdx] = newValue; //模拟写数据,这里是简单赋值
printf("write thread, idx(%d), set value to %d!\n", memIdx, g_mems[memIdx]);
sleepTime = rand() % 1500;
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
printf("write thread, idx(%d), after %d ms sleep, continue to work!\n", memIdx, sleepTime);
int oldValue = g_mems[memIdx];
g_mems[memIdx]++; //模拟写数据,这里是简单自增
printf("write thread, idx(%d),set new value to %d,the old value (%d) will not read by other thread, because we has not unlock source yet!\n", memIdx, g_mems[memIdx], oldValue);
{
std::unique_lock<std::mutex> lock(gl_mutex);
g_memsLockFlag[memIdx] = false;
}
printf("write thread, idx(%d), finished work and unlock source!\n", memIdx);
g_cv.notify_all();
}
int main()
{
srand(time(NULL));
std::thread rt[THREAD_COUNT_FOR_TEST];
std::thread wt[THREAD_COUNT_FOR_TEST];
for (int i = 0; i < THREAD_COUNT_FOR_TEST; ++i)
{
wt[i] = std::thread(wirteTread, i,rand());
rt[i] = std::thread(readTread, i, rand());
}
for (int i = 0; i < THREAD_COUNT_FOR_TEST; ++i)
{
wt[i].join();
rt[i].join();
}
return 0;
}