- 论坛徽章:
- 0
|
本帖最后由 spxjtu 于 2010-04-04 23:39 编辑
能运行一段时间,然后报内存的错误,double free,应该是consumer线程的函数,不知道为什么会两次free呢?
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
struct msg{
struct msg *next;
int num;
}; //生产消费的对象
struct msg *head;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *consumer(void *p)
{
struct msg *mp;
int i;
for(i = 0; i < 10; i ++)
{
pthread_mutex_lock(&lock);
while(head == NULL)
pthread_cond_wait(&has_product, &lock);
mp = head;
head = mp -> next; //消费者取出连表中第一个结构体的数字,然后指针后移
pthread_mutex_unlock(&lock);
printf("Consume %d\n", mp -> num);
free(mp); //报错double free,应该就是这句,不知道为什么
sleep(rand() % 5);
}
}
void *producer(void *p)
{
struct msg *mp;
struct msg *loc;
int i;
for(i = 0; i < 10; i ++)
{
mp = malloc(sizeof(struct msg));
mp -> num = rand() % 1000 + 1;
printf("Produce %d\n", mp -> num);
pthread_mutex_lock(&lock);
if(head == NULL) //将生产的结构依次插入head的链表里
{
head = mp;
loc = mp;
}
loc -> next = mp;
loc = mp; //head指向生成的链表的头部,loc指向最后一个元素
pthread_mutex_unlock(&lock);
sleep(rand() % 5);
}
}
int main(int argc, char ** argv)
{
pthread_t pid, cid;
srand(time(NULL));
pthread_create(&pid, NULL, producer, NULL);
pthread_create(&cid, NULL, consumer, NULL);
pthread_join(pid, NULL);
pthread_join(cid, NULL);
return 0;
} |
|