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

多线程安全 #160

Closed
zjzjzjzj1874 opened this issue Jan 9, 2024 · 1 comment
Closed

多线程安全 #160

zjzjzjzj1874 opened this issue Jan 9, 2024 · 1 comment

Comments

@zjzjzjzj1874
Copy link

// Enqueue put element into queue
func (q *CircularQueue[T]) Enqueue(value T) error {
	if q.IsFull() {
		return errors.New("queue is full!")
	}

	q.data[q.rear] = value
	q.rear = (q.rear + 1) % q.capacity

	return nil
}
// Dequeue remove head element of queue and return it, if queue is empty, return nil and error
func (q *CircularQueue[T]) Dequeue() (*T, error) {
	if q.IsEmpty() {
		return nil, errors.New("queue is empty")
	}

	headItem := q.data[q.front]
	var t T
	q.data[q.front] = t
	q.front = (q.front + 1) % q.capacity

	return &headItem, nil
}

上面两个方法没有加锁,会不会存在并发安全问题?
是不是只能自己在外部调用的时候加锁呢?

@duke-git
Copy link
Owner

duke-git commented Jan 9, 2024

@zjzjzjzj1874, datastructure包下面的数据结构设计就是线程不安全的,需要在外部调用的时候加锁。

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

2 participants