У меня есть 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;
У меня есть глобальная переменная head.
queue *head;
В основном я malloc глава очереди.
head = (queue *)malloc(sizeof(queue));
И вызовите его в другой функции
if(head->elem == NULL) { head = newPointer; }
Когда я делаю голову, все в порядке. Затем, когда он переходит к функции, он сбрасывается до 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(¬Full, &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(¬Empty);
pthread_mutex_unlock(&the_mutex);
usleep(100000); //let others have a chance
}
}