exampleThread.cpp
This is an example for the usage of the
Thread class and Mutexed Resource. More details about this example.
#include <Thread.h>
using namespace MipBaselib;
class IUseThread{
private:
Thread _thread;
int _state;
public:
IUseThread();
void doWork(){
_state ++;
cout << "TID " << pthread_self() << ", I Work " << _state << endl;
};
void doClean(){
_state = 0;
cout << "TID " << pthread_self() << " I Clean " << endl;
};
void startWork(){
_thread.startWork();
}
void stopWork(){
_thread.stopWork();
}
};
extern "C" void work(void* p){
IUseThread* IUTp = (IUseThread*) p;
IUTp->doWork();
}
extern "C" void clean(void* p){
IUseThread* IUTp = (IUseThread*) p;
IUTp->doClean();
}
IUseThread::IUseThread() {
_state = 0;
_thread.setWorkObject(this);
_thread.setWork(work);
_thread.setWorkClean(clean);
_thread.setSleepTime(Time(0,100000));
}
class MutExedResource{
private:
EnhancedMutEx _eMutEx;
public:
bool askExclusiveAccess(Time timeout){
return _eMutEx.askExclusiveAccess(timeout);
}
void leaveExclusiveAccess(){
_eMutEx.leaveExclusiveAccess();
}
bool getOrPutSomething1(){
if(!_eMutEx.allowed()) return false;
cout << "you are using me" << endl;
return true;
}
bool getOrPutSomething2(){
if(!_eMutEx.allowed()) return false;
cout << "you are using me" << endl;
return true;
}
};
class IUseMutExedResource{
private:
MutExedResource _mutExedResource;
public:
bool useMuTexedResource(){
if(_mutExedResource.askExclusiveAccess(Time(0,100))){
_mutExedResource.getOrPutSomething1();
_mutExedResource.getOrPutSomething2();
_mutExedResource.leaveExclusiveAccess();
}
}
};
int main(int argc,const char* argv[]){
IUseThread iUseThread;
for(int i=0; i<2; i++){
cout << "TID " << pthread_self() << ", I start the work" << endl;
iUseThread.startWork();
Timer timer;
while(timer.get() < Time(2,0)){
cout << "TID " << pthread_self() << ", I make something else" << endl;
usleep(500000);
}
iUseThread.stopWork();
cout << "TID " << pthread_self() << ", I've stopped the work" << endl;
}
return 0;
}