Skip to content

Commit d21008e

Browse files
authored
Add Thread::LinkedList#each to safely iterate lists (#15300)
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(&)`.
1 parent 7954027 commit d21008e

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

src/crystal/system/thread.cr

+4
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ class Thread
7474
@@threads.try(&.unsafe_each { |thread| yield thread })
7575
end
7676

77+
def self.each(&)
78+
threads.each { |thread| yield thread }
79+
end
80+
7781
def self.lock : Nil
7882
threads.@mutex.lock
7983
end

src/crystal/system/thread_linked_list.cr

+7
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ class Thread
2424
end
2525
end
2626

27+
# Safely iterates the list.
28+
def each(&) : Nil
29+
@mutex.synchronize do
30+
unsafe_each { |node| yield node }
31+
end
32+
end
33+
2734
# Appends a node to the tail of the list. The operation is thread-safe.
2835
#
2936
# There are no guarantees that a node being pushed will be iterated by

src/fiber.cr

+5
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,11 @@ class Fiber
7878
@@fibers.try(&.unsafe_each { |fiber| yield fiber })
7979
end
8080

81+
# :nodoc:
82+
def self.each(&)
83+
fibers.each { |fiber| yield fiber }
84+
end
85+
8186
# Creates a new `Fiber` instance.
8287
#
8388
# When the fiber is executed, it runs *proc* in its context.

0 commit comments

Comments
 (0)