我是 C++ 的新手,正在研究应该是一个非常基本的文件读取然后处理数据功能,我一直坚持能够至少向另一个线程提供“状态”,以便可以使用数据。这可能只是我忽略的一些非常基本的东西 - 可以使用一些洞察力来了解在 c++ 中使用 pthreads。
Bellow 是一些基本的提取代码,可以正常运行,读取文件并提供要处理的数据。另一个将处理数据的线程需要知道这个线程的状态。最好的策略是什么?我试图通过另一个线程的函数请求线程的状态,但收到不正确的响应。
Reader::Reader(){
_threadId = 1;
_msg = NONE; // enum NONE, READ, STOP
active = false;
pthread_mutex_init(&_mutex, 0);
}
Reader::~Reader(){
pthread_mutex_destroy(&_mutex);
}
void Reader::read(){
_msg = READ;
active = true;
pthread_create(&_threadId, 0, work, this);
}
void * Reader::work(void *myselfreader){
Reader * reader = (Reader*)myselfreader;
reader->loop();
pthread_exit(0);
return 0;
}
void Reader::loop(){
while(active){
pthread_mutex_lock(&_mutex);
switch(_msg){
case READ:
// do the reading of the IO file - which works fine
// once done reading the file - the _msg is set to STOP
break;
case STOP:
stopThread();
break;
default:
break;
}
pthread_mutex_unlock(&_mutex);
}
return;
}
void Reader::stopThread(){
active = false;
_msg = ENC_NONE;
pthread_join(_threadId, 0);
}
/*****************/
int Reader::getReaderState(){
// another thread needs to know the state of this thread
//
return _msg // ??
return active // ??
}