最近在看posix多线程程序设计,第四章中流水线的例子中,建立链表的方法比较独特,之前没看到过,还是自己代码写得少。例子如下代码
int pipe_index;
stage_t **link = &pipe->head, *new_stage, *stage;
int status;
status = pthread_mutex_init (&pipe->mutex, NULL);
if (status != 0)
err_abort (status, "Init pipe mutex");
pipe->stages = stages;
pipe->active = 0;
for (pipe_index = 0; pipe_index <= stages; pipe_index++) {
new_stage = (stage_t*)malloc (sizeof (stage_t));
if (new_stage == NULL)
errno_abort ("Allocate stage");
status = pthread_mutex_init (&new_stage->mutex, NULL);
if (status != 0)
err_abort (status, "Init stage mutex");
status = pthread_cond_init (&new_stage->avail, NULL);
if (status != 0)
err_abort (status, "Init avail condition");
status = pthread_cond_init (&new_stage->ready, NULL);
if (status != 0)
err_abort (status, "Init ready condition");
new_stage->data_ready = 0;
*link = new_stage;
link = &new_stage->next;
}
*link = (stage_t*)NULL; /* Terminate list */
pipe->tail = new_stage; /* Record the tail */
这里运用指针的指针来创建单链表。
我的理解是:首先link是指向*link的,循环开始之前,link指向*link,*link指向head所指向的内存单元,第一次循环执行完*link = new_stage;此时*link指向了new_stage所指内存单元,执行link = &new_stage->next之后,link地址内存单元的内容是new_stage->next,即link指向了内存单元内容为:new_stage->next,通过对*link的修改也会造成new_stage->next被修改,所以下次循环之后*link指向了一个新的内存单元,也会使得new_stage->next指向该单元,如此单链表便可以连接起来。
测试程序如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct stage_tag
{
int data_ready;
long data;
struct stage_tag *next;
}stage_t;
stage_t *list_create(int stages)
{
int index;
stage_t *head = NULL, *tail = NULL;
stage_t **link = &head, *new_stage, *stage;
for (index = 0; index < stages; index++)
{
new_stage = (stage_t*) malloc (sizeof(stage_t));
if (new_stage == NULL)
{
printf("new_stage is null\n");
return -1;
}
new_stage->data_ready = 0;
new_stage->data = index;
*link = new_stage;
link = &new_stage->next;
}
*link = (stage_t*)NULL;
tail = new_stage;
return head;
}
int main()
{
stage_t *head = list_create(4);
while(head)
{
printf("data:%d\n", head->data);
head = head->next;
}
return 0;
}
结果如下:
data:0
data:1
data:2
data:3