Skip to content

Locally copy queue to avoid holding lock while Actions execute. #14

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.meta
18 changes: 12 additions & 6 deletions UnityMainThreadDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,18 @@ public class UnityMainThreadDispatcher : MonoBehaviour {
private static readonly Queue<Action> _executionQueue = new Queue<Action>();

public void Update() {
lock(_executionQueue) {
while (_executionQueue.Count > 0) {
_executionQueue.Dequeue().Invoke();
}
}
}
// Make local copy to avoid holding the lock while the actions execute.
Queue<Action> queueCopy;
lock (_executionQueue)
{
queueCopy = new Queue<Action>(_executionQueue);
_executionQueue.Clear();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the reason for clearing the queue here? Because it's being moved over to an entirely new queue? I get the idea but it seems a lot can go wrong here.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you say more about what could go wrong?

The copy-and-clear step is effectively the same as the previous while-not-empty-dequeue; we're just moving the Invoke step outside of the lock. The invariant from the original implementation should still be the same - that each action in _executionQueue when Update is called gets executed on the main thread and that those actions are no longer in the queue.

This just means background threads only wait for a queue to copy instead of arbitrarily expensive actions to execute. (Admittedly, if the actions are that expensive, they likely shouldn't be executing on the main thread, but that's a different issue).

}
while (queueCopy.Count > 0)
{
queueCopy.Dequeue().Invoke();
}
}

/// <summary>
/// Locks the queue and adds the IEnumerator to the queue
Expand Down