the variable _Mtx_t failed and references null. How i declare it in order to all his function doesn't fail?
#include <iostream>
#include <stdio.h>
#include <thread>
#include <conio.h>
#include <mutex>
#include <signal.h>
#include <condition_variable>
#define NUM_READERS 6
#define NUM_READS 5
#define NUM_WRITERS 6
#define NUM_WRITES 5
using namespace std;
_Cnd_t read_phase, write_phase;
int resource_counter = 0;
_Mtx_t counter_mutex = (_Mtx_t)("0x01", "0x02", "0x04", "0x100");
int WaitReaders = 0,Read = 0;
void writer() {
int i = 0, numReaders = 0;
for (i = 0; i < NUM_WRITES; i++) {
_Mtx_trylock(counter_mutex); {
while (Read != 0) {
_Cnd_wait(write_phase, counter_mutex);
}
Read = -1;
numReaders = Read;
}
_Mtx_unlock(counter_mutex);
printf( " writing %u* [readers: %2d]\n", ++resource_counter, numReaders);
_Mtx_lock(counter_mutex); {
Read = 0;
if (WaitReaders > 0)
_Cnd_broadcast(read_phase);
else
_Cnd_signal(write_phase);
}
_Mtx_unlock(counter_mutex);
counter_mutex;
}
}
void Readers() {
int i = 0, numReaders = 0;
for (i = 0; i < NUM_READS; i++) {
_Mtx_lock(counter_mutex);
{
while (resource_counter == 1)
{
_Cnd_wait(read_phase, counter_mutex);
}
WaitReaders--;
numReaders = ++Read;
}
_Mtx_unlock(counter_mutex);
}
printf( " reading %u [readers: %2d]\n", resource_counter, numReaders);
_Mtx_lock(counter_mutex); {
Read--;
if (Read == 0)
_Cnd_signal(read_phase);
}
_Mtx_unlock(counter_mutex);
}
int main()
{
int i;
int readerNum[NUM_READERS];
int writerNum[NUM_WRITERS];
thread readerThreadIDs[NUM_READERS];
thread writerThreadIDs[NUM_WRITERS];
for (i = 0; i < NUM_READERS; i++) {
readerNum[i] = i;
readerThreadIDs[i] = thread(Readers);
writerNum[i] = i;
writerThreadIDs[i] = thread(writer);
}
for (i = 0; i < NUM_READERS; i++) {
readerThreadIDs[i].join();
writerThreadIDs[i].join();
}
return 0;
}
Exception thrown at 0x79969664 (msvcp140d.dll) in Priority Readers and Writers.exe: 0xC0000005: Access violation reading location 0x00000030.
Unhandled exception thrown: read access violation.
_Mtx_internal_imp_t::_get_cs(...)->**** was 0x30. occurred
_Cnd_t
? _Mtx_t
? These are types which are internal to your C++ implementation, and they are not intended to be used by you.
You should use std::mutex
and std::condition_variable
. Look them up in your C++ book.
User contributions licensed under CC BY-SA 3.0