我正在尝试模拟同时读写。由于某种原因,线程不会同时执行此操作。我创建了2个线程,这些线程包含一个Sleep(0),因此其他线程可以在那里进行处理。在我创建新对象的部分,我甚至睡了一觉:
delete this->item; this->item = 0; Sleep(0); this->item = new hallo();
我在发布模式下运行此测试约2小时。没有例外或崩溃。我做错了什么?
这是我尝试这样做的方式:
#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;
}
这些是类:
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(); }
};
仅供参考: