多线程条件变量无法唤醒
我简单描述一下场景:
有一个主函数和一个线程,线程里有一个自定义的数据队列。当队列中没有数据时,线程wait。
主函数负责将数据按一定算法切分成小数据块,然后将数据放到线程的数据队列中,然后发signal给线程,线程对数据进行处理。主要代码如下:
主函数放数据的方法:
void pushData(SliceArg* arg){
pthread_mutex_lock(&threadpool[0]->lock);
threadpool[0]->queue_.push_back(arg);
pthread_cond_signal(&threadpool[0]->cv);
pthread_mutex_unlock(&threadpool[0]->lock);
}
其中的threadpool有多个线程,0即为要处理数据的线程,queue_是它的数据队列。
线程的主要代码:
void run(){
while(true){
pthread_mutex_lock(&lock);
while(queue_.empty())
pthread_cond_wait(&cv, &lock);
SliceArg* arg = queue_.front();
queue_.pop_front();
doTask(arg);
pthread_mutex_unlock(&lock);
}
}
其中lock和cv都是线程直接的成员变量。
现在的问题是,程序开始时,线程进入等待,但主函数调用signal以后,线程并没有被唤醒。
请问各位大牛,问题会出在什么地方啊?
------解决方案--------------------
仅供参考//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#ifdef WIN32
#pragma warning(disable:4996)
#endif
#include
#include
#include
#ifdef WIN32
#include
#include
#include
#define MYVOID void
#define vsnprintf _vsnprintf
#else
#include
#include
#include
#define CRITICAL_SECTION pthread_mutex_t
#define MYVOID void *
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include
#include
#include
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef WIN32
void Lock(CRITICAL_SECTION *l) {
EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
LeaveCriticalSection(l);
}
void sleep_ms(int ms) {
Sleep(ms);
}
#else
void Lock(CRITICAL_SECTION *l) {
pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
pthread_mutex_unlock(l);
}
void sleep_ms(int ms) {
usleep(ms*1000);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
struct tm *now;
struct timeb tb;
if (NULL==pszFmt
------解决方案--------------------
0==pszFmt[0]) return;
vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
ftime(&tb);
now=localtime(&tb.time);
sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
sprintf(timestr,"%02d:%02d:%02d",now->tm_hour ,now->tm_min ,now->tm_sec );
sprintf(mss,"%03d",tb.millitm);
printf("%s %s.%s %s",datestr,timestr,mss,logstr);
flog=fopen(logfilename1,"a");
if (NULL!=flog) {
fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
if (ftell(flog)>MAXLOGSIZE) {
fclose(flog);
if (rename(logfilename1,logfilename2)) {
remove(logfilename2);
rename(logfilename1,logfilename2);
}
} else {
fclose(flog);
}
}
}
void Log(const char *pszFmt,...) {
va_list argp;
Lock(&cs_log);