Skip to content

Commit

Permalink
Add Thread::LinkedList#each to safely iterate lists (#15300)
Browse files Browse the repository at this point in the history
Sometimes we'd like to be able to safely iterate the lists. Also adds `Thread.each(&)` and `Fiber.each(&)` as convenience accessors.

This will be used in RFC 2 to safely iterate execution contexts for example.

Also adds `Thread.each(&)` and `Fiber.each(&)`.
  • Loading branch information
ysbaddaden authored Dec 25, 2024
1 parent 7954027 commit d21008e
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/crystal/system/thread.cr
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ class Thread
@@threads.try(&.unsafe_each { |thread| yield thread })
end

def self.each(&)
threads.each { |thread| yield thread }
end

def self.lock : Nil
threads.@mutex.lock
end
Expand Down
7 changes: 7 additions & 0 deletions src/crystal/system/thread_linked_list.cr
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ class Thread
end
end

# Safely iterates the list.
def each(&) : Nil
@mutex.synchronize do
unsafe_each { |node| yield node }
end
end

# Appends a node to the tail of the list. The operation is thread-safe.
#
# There are no guarantees that a node being pushed will be iterated by
Expand Down
5 changes: 5 additions & 0 deletions src/fiber.cr
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ class Fiber
@@fibers.try(&.unsafe_each { |fiber| yield fiber })
end

# :nodoc:
def self.each(&)
fibers.each { |fiber| yield fiber }
end

# Creates a new `Fiber` instance.
#
# When the fiber is executed, it runs *proc* in its context.
Expand Down

0 comments on commit d21008e

Please sign in to comment.