I attend to working RWLock with 5 thread ( 4 threads for reading and 1 thread for writing ), reference(&) operator and without using mutex library
I want to make a thread array and insert the their jobs, and working. but when i had a breakpoint to funtion ReadLock, i got a value 5. It means threads are inserted last value of threadNum. It didn't attend ( i think threads are working once)
My question is how to insert correctly their values and work correctly
code is below
#include <iostream>
#include <thread>
#include <windows.h>
void ReadLock(bool& try_w_lock, bool*& readFlag, int threadNum, int& Val);
void WriteLock(bool& try_w_lock, bool*& readFlag, int& Val);
int main()
{
std::thread th[5];
bool try_w_lock = false;
bool Flag[5] = { false, };
bool* readFlag = Flag;
int Val = 0;
int threadNum = 0;
for ( ; threadNum < 4; ++threadNum)
{
th[threadNum].operator=( std::thread([&]() {ReadLock(try_w_lock, readFlag, threadNum, Val); }));
}
for ( ; threadNum < 5; ++threadNum)
{
th[threadNum].operator=(std::thread([&]() {WriteLock(try_w_lock, readFlag, Val); }));
}
for (auto& d : th)
{
d.join();
}
}
void ReadLock(bool& try_w_lock, bool*& readFlag, int threadNum, int& Val)
{
while (Val < 100)
{
while (try_w_lock);
(readFlag)[threadNum] = true;
std::cout << Val << std::endl;
(readFlag)[threadNum] = false;
Sleep(500);
}
}
void WriteLock(bool& try_w_lock, bool*& readFlag, int& Val)
{
while (Val <100)
{
try_w_lock = true;
while (true)
{
bool b = false;
for (int i = 0; i < 5; ++i)
{
b = b | (readFlag)[i];
}
if (!b)
break;
else;
}
++Val;
try_w_lock = false;
Sleep(500);
}
}