gpt4 book ai didi

C多线程malloc坏访问全局

转载 作者:太空宇宙 更新时间:2023-11-04 06:43:14 31 4
gpt4 key购买 nike

我有 2 个结构如下:

typedef struct _product
{
unsigned int product_id;
time_t my_time_stamp;
unsigned int lifespan;
} product;

typedef struct _queue
{
product * elem;
struct _queue * next;
} queue;

我有一个全局变量头。

queue *head; 

在 main 中,我 malloc 队列的头部。

head = (queue *)malloc(sizeof(queue));

然后在另一个函数中调用它

    if(head->elem == NULL) { head = newPointer; }

当我 malloc 头部时,一切都很好。然后,当它跳转到该函数时,它会重置为 0x0。

这是错误的做法吗?如果可以,应该怎么做?

void producer_func(void *tid)
{
while(number_of_products_created < number_of_products_max) //check for completeness of task
{
my_str("in producer with id ");
my_int((long)tid);
br();
pthread_mutex_lock(&the_mutex);
my_str("locked by ");
my_int((long)tid);
br();
while(space_in_queue >= size_of_queue)
pthread_cond_wait(&notFull, &the_mutex); //check to see if there is room in the queue

product *tempProduct = malloc(sizeof(product));

//////////////enter critical region/////////////
tempProduct->product_id = product_id_count++;
//////////////exit critical region/////////////

//time
struct timeval tim;
gettimeofday(&tim, NULL);
tempProduct->my_time_stamp = tim.tv_sec;
//endtime
tempProduct->lifespan = rand();
//new item for queue
queue *newPointer = malloc(sizeof(queue));
newPointer->elem = tempProduct;
newPointer->next = NULL;

//critical region//
if(head == NULL)
{
head = newPointer;
}
else
{
//traverse list
queue *tempPointer;
tempPointer = head;
while(tempPointer->next != NULL)
{
tempPointer = tempPointer->next;
}
tempPointer->next = newPointer;
}
space_in_queue++;
number_of_products_created++;
//end critical region//

my_str("unlocked by ");
my_int((long)tid);
br();
usleep(10000);
my_str("num products created is ");
my_int(number_of_products_created);
br();
usleep(10000);
pthread_cond_broadcast(&notEmpty);
pthread_mutex_unlock(&the_mutex);
usleep(100000); //let others have a chance
}
}

最佳答案

在锁定互斥量和释放它之间有大量代码。您的目标应该是尽量减少持有锁时完成的工作量。你应该做所有的工作,除了在没有锁的情况下将项目添加到列表中。只有当一切准备就绪时,您才能获取互斥量并继续添加项目并释放互斥量。在列表末尾添加项也是一个 O(1) 而不是 O(N) 操作的好主意——保持指向结构尾部的指针。如果您在互斥锁保持锁定的情况下一次休眠 10 毫秒,您真的不会从系统中获得良好的性能(并发性)。

另一个批评是您的产品结构在许多 64 位平台上将占用 24 个字节,而不仅仅是 16 个。如果 time_t 是一个 8 字节的数量并且 8 字节的数量在 8 上对齐-字节边界,您在每个 unsigned int 值之后浪费了 4 个字节。

但是,这只是一般性的批评 - 并不是您问题的直接根源。


实质性的

您似乎没有初始化使用 malloc() 分配的 queue。由于 malloc() 返回未初始化的数据,因此它可以包含任何内容。在你做任何其他事情之前,你必须把它变成一个正确形成的队列项——带有初始化的指针等。

关于C多线程malloc坏访问全局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5085934/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com