Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请教一下, 为什么是用链表? #40

Open
yangliyl opened this issue May 26, 2021 · 2 comments
Open

请教一下, 为什么是用链表? #40

yangliyl opened this issue May 26, 2021 · 2 comments

Comments

@yangliyl
Copy link

func (b *bucket) Flush(reinsert func(*Timer)) {
	var ts []*Timer

	b.mu.Lock()
	for e := b.timers.Front(); e != nil; {
		next := e.Next()

		t := e.Value.(*Timer)
		b.remove(t)
		ts = append(ts, t)

		e = next
	}
	b.mu.Unlock()

	b.SetExpiration(-1) // TODO: Improve the coordination with b.Add()

	for _, t := range ts {
		reinsert(t)
	}
}

bucket为什么是用链表呢? 没有体会到它的作用.
添加task的时候直接追加的数组尾部, 到期时直接遍历数组取出所有task. 因为每个bucket里的task到期时间都是一样的, 那直接用数组不行吗?
请大佬解惑

@tobyzxj
Copy link

tobyzxj commented Oct 6, 2021

数组是确定大小的,并且添加和删除都需要自己维护索引,操作比较复杂,list数据结构就比较简单了。

@RussellLuo
Copy link
Owner

感谢 @tobyzxj 帮忙回复!

添加task的时候直接追加的数组尾部, 到期时直接遍历数组取出所有task.

我稍微补充一下:

  1. 数组扩容时会 copy 数据,不如链表高效
  2. timer.Stop() 可能会从任意位置删除元素,链表最适合这种操作

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants