I’m trying to simulate a simultaneous read and write. For some reason the threads won’t do this at the same time. I create 2 threads, these threads contain a Sleep(0) so other threads can do there processing. In the part where I create a new object I even put a sleep:
delete this->item; this->item = 0; Sleep(0); this->item = new hallo();
I ran this test for around 2 hours in release mode. There was no exception or crash. What do I do wrong?
This is how I try to do this:
#include <Windows.h>
#include <stdio.h>
#include "Source.h"
DWORD WINAPI readVar(LPVOID);
DWORD WINAPI writeVar(LPVOID);
testclass * testobject;
int main()
{
testobject = new testclass();
CreateThread(NULL,NULL,readVar,NULL,NULL,NULL);
CreateThread(NULL,NULL,writeVar,NULL,NULL,NULL);
while(true)
Sleep(10000);
}
DWORD WINAPI readVar(LPVOID)
{
while(true)
{
hallo * testObjectTest = testobject->getValue();
if(!testObjectTest->outpoutSomeData())
printf("ERROR\n\n");
Sleep(0);
}
return NULL;
}
DWORD WINAPI writeVar(LPVOID)
{
while(true)
{
testobject->resetValue();
Sleep(0);
}
return NULL;
}
These are the classes:
class hallo
{
public:
hallo() {printf("Object created\n");}
~hallo() {printf("Object removed\n");}
bool outpoutSomeData() { printf("Call\n"); return true; }
};
class testclass
{
private:
hallo * item;
public:
testclass() {this->item = new hallo(); }
hallo * getValue() { return item; }
void resetValue() { delete this->item; this->item = 0; Sleep(0); this->item = new hallo(); }
};
FYI:
- This is just a simple test. I didn’t pay much attention to “good coding”;
- I have 4 CPU cores, so it need to be possible.
- I had this problem multiple times in other programs, i fixed that with locking. Now I want to create a test where this will happen. But it won't work.