Created
February 11, 2018 10:53
-
-
Save ViteFalcon/4e40e72cff9c0dbcff35e36271c7c893 to your computer and use it in GitHub Desktop.
Thread-safe circular buffer queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
var array | |
var size | |
var start = 0 | |
var end = -1 | |
var mutex = Mutex.new() | |
signal item_removed | |
func _init(max_size): | |
array = [] | |
for i in range(max_size): | |
array.append(null) | |
size = 0 | |
func _get_next_index(index): | |
var next_index = index + 1 | |
if next_index >= len(array): | |
return 0 | |
return next_index | |
func is_empty(): | |
return size > 0 | |
func push(object): | |
if size == len(array): | |
yield(self, "item_removed") | |
mutex.lock() | |
end = _get_next_index(end) | |
size += 1 | |
array[end] = object | |
mutex.unlock() | |
func pop(): | |
if size < 1: | |
return null | |
mutex.lock() | |
var item = array[start] | |
array[start] = null | |
start = _get_next_index(start) | |
size -= 1 | |
mutex.unlock() | |
emit_signal("item_removed") | |
return item |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment