LinkedList: Add a convenience delayed_for_each() method.

This is a special way of iterating over the list which permits removing items while iterating.
This commit is contained in:
apio 2022-12-19 12:41:25 +01:00
parent 5b72144fac
commit 1269a045bd
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 16 additions and 15 deletions

View File

@ -182,25 +182,14 @@ namespace Scheduler
{
DoublyLinkedList<Thread> result;
Thread* thread_to_remove = nullptr;
g_threads.for_each([&](Thread* thread) {
if (thread_to_remove)
g_threads.delayed_for_each([&](Thread* thread) {
if (thread->state == ThreadState::Dying)
{
g_threads.remove(thread_to_remove);
result.append(thread_to_remove);
g_threads.remove(thread);
result.append(thread);
}
if (thread->state == ThreadState::Dying) { thread_to_remove = thread; }
else { thread_to_remove = nullptr; }
});
if (thread_to_remove)
{
g_threads.remove(thread_to_remove);
result.append(thread_to_remove);
}
return result;
}
}

View File

@ -161,6 +161,18 @@ template <typename T> class DoublyLinkedList
for (Node* node = m_start_node; node; node = node->get_next()) { callback((T*)node); }
}
// Iterates over the elements of the DoublyLinkedList from start to end, calling callback for every element. This
// for_each is implemented in such a way that elements can be removed while iterating over it.
template <typename Callback> void delayed_for_each(Callback callback)
{
for (Node* node = m_start_node; node;)
{
T* current = (T*)node;
node = node->get_next();
callback(current);
}
}
// Iterates over the elements of the DoublyLinkedList from end to start, calling callback for every element.
template <typename Callback> void for_each_reversed(Callback callback)
{