我正在进行网络编程,并创建了一个线程池。它基本上具有互斥锁和条件变量的队列,5个子线程竞争从队列中获取工作。看起来像使用条件变量锁定和解锁正确工作。在单独的线程上同时调用一个函数
但问题是,如果我从子线程调用一个函数,那么只允许一个线程在函数(fromByte)上工作。例如,如果线程1调用该函数,那么另一个线程将不能进入该函数。
void WorkHandler::workLoop(){
printf("WorkHandler::workLoop, called\n");
while(m_workHandlerRun){
Work *work = getWork();
char *pdata = work->getMsg();
/*
* Get type only
*/
unsigned char type = pdata[0];
printf("WorkHandler::workLoop, type %d\n", type);
Packet *packet = m_packetFactory->createInstance(static_cast<PACKET_TYPES>(type));
packet->fromByte(pdata);
}
}
这是工作循环,在子线程运行,它从工厂获得适当的类的实例后,它会调用fromByte()。如果我看到日志语句,则只允许一个线程在fromByte函数上工作,并且如果线程完成,则其他线程可以在该函数中工作。换句话说,如果一个线程当前在该函数中,则其他线程将等待线程完成工作。
bool WorkHandler::initThreads(){
for(int i=0; i < m_maxThreads; i++){
pthread_t *thread(new pthread_t);
m_workThreadList.push_back(thread);
if(pthread_create(thread, NULL, runWorkThread, reinterpret_cast<void *>(this))!=0){
perror("WorkHandler::initThreads, pthread_create error \n");
return false;
}
pthread_detach(*thread);
}
return true;
}
这是我如何产生一个线程和runWorkThread是一个静态方法来调用workLoop函数。如何修复我的代码,以便子线程可以同时处理该函数。在此先感谢..
编辑
我锁定和解锁这样
void WorkHandler::addWork(Work* w){
printf("WorkHandler::insertWork Thread, insertWork locking \n");
lock();
printf("WorkHandler::insertWork Locked, and inserting into queue \n");
m_workQueue.push(w);
signal();
unLock();
}
Work* WorkHandler::getWork(){
printf("WorkHandler::getWork, locking (tid : %lu) \n", pthread_self());
lock();
printf("WorkHandler::getWork, locked (tid : %lu) \n", pthread_self());
while(m_workQueue.empty()){//Need 'while' instead of 'If'
printf("WorkHandler::getWork, waiting... (tid : %lu) \n", pthread_self());
wait();
printf("WorkHandler::getWork, waiting DONE (tid : %lu) \n", pthread_self());
}
Work *work = m_workQueue.front();
printf("WorkHandler::getWork, got a job (tid : %lu) \n", pthread_self());
m_workQueue.pop();
unLock();
return work;
}
而且,这个类扩展MutexdCondtion类我创建 MutexCondition.cpp文件
bool MutexCondition::init(){
printf("MutexCondition::init called\n");
pthread_mutex_init(&m_mut, NULL);
pthread_cond_init(&m_con, NULL);
return true;
}
bool MutexCondition::destroy(){
pthread_mutex_destroy(&m_mut);
pthread_cond_destroy(&m_con);
return true;
}
bool MutexCondition::lock(){
pthread_mutex_lock(&m_mut);
return true;
}
bool MutexCondition::unLock(){
pthread_mutex_unlock(&m_mut);
return true;
}
bool MutexCondition::wait(){
pthread_cond_wait(&m_con, &m_mut);
return true;
}
bool MutexCondition::signal(){
pthread_cond_signal(&m_con);
return true;
}
这都是ireleavent。你如何锁定该方法? –