|
最近在开发的过程中涉及到两个线程对同一个内存数据进行操作,写了一段实验代码,结果完全达不到效果。- class MetaData
- {
- public:
- MetaData(void);
- MetaData(int dataArray[10]);
- ~MetaData(void);
- void setDataArray(int dataArray[10]);
- void setDataArray(int index,int value);
- int* getDataArray();
- int getDataArray(int index);
- private:
- int dataArray[10];
- };
复制代码 这个是要操作的元数据。
写了两个线程,WriteThread和ReadThread来实现对元数据的读写操作。- class WriteThread :
- public OpenThreads::Thread
- {
- public:
- WriteThread(void);
- WriteThread(int index,int value,MetaData* metaData);
- ~WriteThread(void);
- virtual int cancel();
- virtual void run();
-
- private:
- int index,value;
- MetaData* metaData;
- OpenThreads::Mutex wirteMutex;
- };
复制代码- class ReadThread :
- public OpenThreads::Thread
- {
- public:
- ReadThread(void);
- ReadThread(int index,MetaData* metaData);
- ~ReadThread(void);
- virtual void run();
- virtual int cancel();
- private:
- OpenThreads::Mutex readMutex;
- int index;
- MetaData* metaData;
- };
复制代码 两个线程类的Run函数分别为:- void WriteThread::run()
- {
- OpenThreads::ScopedLock<OpenThreads::Mutex> wirterLock(this->wirteMutex);
- for(int i=0;i<10;i++)
- {
- std::cout<<"write is running "<<std::endl;
- this->metaData->setDataArray(this->index,this->value);
- this->microSleep(150000L);
- }
-
- }
复制代码- void ReadThread::run()
- {
- OpenThreads::ScopedLock<OpenThreads::Mutex> readLock(this->readMutex);
-
- for(int i=0;i<10;i++)
- {
- std::cout<<"read is running"<<std::endl;
- //this->metaData->setDataArray(this->index,3);
- std::cout<<"the "<<this->index<<" value is "<<this->metaData->getDataArray(this->index)<<std::endl;
- this->microSleep(150000L);
- }
-
-
-
- }
复制代码 主函数里面的调用为:- int main()
- {
-
-
- MetaData* metaData = new MetaData();
- int index = 0,value = 10;
- WriteThread write(index,value,metaData);
- ReadThread read(index,metaData);
- read.start();
- write.start();
- }
复制代码 本来想实现read线程读取完毕之后,write线程才可以操作元数据,结果这样写了之后发现两者是同时运行的。
本文对多线程了解不深,望高人指点。 |
|