这段代码有以下问题。有人可以帮忙吗?
注意: QueueItem 是在不同的线程上创建的。
WorkItem * Dequeue(Queue ** Q)
{
if(QueueIsEmpty(*Q)) return NULL;
QueueItem * tmp = (*Q)->Head;
(*Q)->Head = ((*Q)->Head)->NextItem;
WorkItem * retval = tmp->workItem;
free(tmp); //Generates glibc detected *** free(): invalid pointer
return retval;
}
编辑当多个线程正在运行时,此功能在访问时受到保护。
WorkItem * DequeueSynchronous(Queue ** Q)
{
WorkItem * retval;
pthread_mutex_lock((*Q)->QueMutex);
retval = Dequeue (Q);
pthread_mutex_unlock((*Q)->QueMutex);
return retval;
}
(*Q)->头部;分配给我的malloc。
Queue * Queue_Init(pthread_mutex_t * mutex)
{
Queue * retval = (Queue *)malloc(sizeof(Queue *));
retval->Head = retval->Tail =NULL;
retval->QueMutex = mutex;
return retval;
}
void Enqueue (Queue * Q, WorkItem * WI)
{
if(!Q)return;
QueueItem * QI = (QueueItem *) malloc(sizeof(QueueItem *));
QI->workItem = WI;
QI->NextItem = NULL;
if(QueueIsEmpty(Q))
{
Q->Head = Q->Tail = QI;
return;
}
Q->Tail->NextItem = QI;
Q->Tail = QI;
}
void EnqueueSynchronous (Queue * Q, WorkItem * WI)
{
pthread_mutex_lock(Q->QueMutex);
Enqueue (Q, WI);
pthread_mutex_unlock(Q->QueMutex);
}
还要感谢您的输入,我会看看 valgrind。
编辑 2
typedef struct {
char ** FileNames;
int ** Results;
int NumOfItems;
}WorkItem;
typedef struct QI{
WorkItem * workItem;
struct QI * NextItem;
}QueueItem;
typedef struct {
QueueItem * Head, * Tail;
pthread_mutex_t * QueMutex;
}Queue;
Dequeue 被调用 -Dequeue(&WorkQue)
所有调用的线程Dequeue
都&WorkQue
作为其参数的一部分给出;
typedef struct{
int ThreadID;
WorkItem * workItem;
char ** keywordsArray;
int nKeywords;
Queue ** WorkQueue, ** WorkCompletedQ;
}ThreadArgs;
pthread_t threads[NTHREADS];
ThreadArgs threadArgs[NTHREADS];
for(i=0;i<NTHREADS;i++)
{
threadArgs[i].ThreadID=i;
threadArgs[i].workItem = Dequeue(&WorkQue);
threadArgs[i].WorkQueue = &WorkQue;
threadArgs[i].WorkCompletedQ = &WorkCompletedQ;
threadArgs[i].nKeywords=_kwlist->length;
threadArgs[i].keywordsArray = ListToArray(*_kwlist);
}
for(i=0;i<NTHREADS;i++)
{
pthread_create(&threads[i], NULL, WorkerThread,(void *)&(threadArgs[i]));
}
每个线程调用 dequeue 使用myWork = DequeueSynchronous(myThreadArgs->WorkQueue);