我正在编写一个带有双链表的简单计时器。如果我将链表头定义如下,它将起作用。
struct timer_head
{
struct timer* prev;
struct timer* next;
pthread_spinlock_t lock;
};
但是如果我将头部定义如下,那么插入就会失败,每次插入后我都会丢失前一个节点。
struct timer_head
{
struct timer* next;
struct timer* prev;
pthread_spinlock_t lock;
};
我的部分代码:
struct timer
{
struct timer* prev;
struct timer* next;
struct timespec start;
struct timespec interval;
void* par, *par2;
/*if handle return 0 */
/*then delete this timer */
/*else restart it */
int (*handler) (void* par);
};
struct timer_head
{
struct timer* prev;
struct timer* next;
/*
*if i changed the previous definition to
*code below, then my list insertion will failed
*why?
*/
/* struct timer* next;
struct timer* prev;
*/
pthread_spinlock_t lock;
};
void timer_queue_init(struct timer_head* lst)
{
pthread_spin_init(&lst->lock, PTHREAD_PROCESS_SHARED);
lst->next = lst->prev = (struct timer*)lst;
}
static void print_queue(struct timer_head* lst)
{
pthread_spin_lock(&(lst->lock));
struct timer* fst = lst->next;
printf("list travserse:\t");
while (fst != (struct timer*) lst)
{
printf("inteval : %ld, ", fst->interval.tv_nsec);
fst = fst->next;
}
printf("\n");
pthread_spin_unlock(&(lst->lock));
}
void timer_queue_insert(struct timer_head* lst, struct timer* nt)
{
pthread_spin_lock(&(lst->lock));
struct timer* ptr = lst->next;
/*insert into list, sorted as earlist execute time */
while (ptr != (struct timer*) lst &&
timespec_cmp(&(ptr->start), &(ptr->interval),
&(nt->start), &(nt->interval)) <= 0)
{
printf("next\n");
ptr = ptr->next;
}
nt->next = ptr;
nt->prev = ptr->prev;
nt->prev->next = nt;
ptr->prev = nt;
/* send signal to manage thread */
if (!qlen)
{
printf("start :%ld s, %ld ns ", nt->start.tv_sec, nt->start.tv_nsec);
printf("interval :%lds, %ld ns\n", nt->interval.tv_sec, nt->interval.tv_nsec);
pthread_cond_signal(&wait);
}
++qlen;
pthread_spin_unlock(&(lst->lock));
printf("traver after insert\t");
print_queue(lst);
}