Skip to content

Commit 0be6ee6

Browse files
Improve Fiber::ExecutionContext.default_workers_count (#16149)
Co-authored-by: Johannes Müller <[email protected]>
1 parent e0a871e commit 0be6ee6

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

src/fiber/execution_context.cr

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,15 +84,22 @@ module Fiber::ExecutionContext
8484
@@monitor = Monitor.new
8585
end
8686

87-
# Returns the number of threads to start in the default multi threaded
88-
# execution context. Respects the `CRYSTAL_WORKERS` environment variable
89-
# and otherwise returns the potential parallelism of the CPU (number of
90-
# hardware threads).
87+
# Returns the default maximum parallelism. Can be used to resize the default
88+
# parallel execution context for example.
9189
#
92-
# Currently unused because the default context is single threaded for
93-
# now (this might change later with compilation flags).
90+
# Respects the `CRYSTAL_WORKERS` environment variable if present and valid,
91+
# and otherwise defaults to the minimum number of logical CPUs available to
92+
# the process or available on the computer.
9493
def self.default_workers_count : Int32
95-
ENV["CRYSTAL_WORKERS"]?.try(&.to_i?) || Math.min(System.cpu_count.to_i, 32)
94+
if count = ENV["CRYSTAL_WORKERS"]?.try(&.to_i?)
95+
return count.clamp(1..)
96+
end
97+
98+
total = System.cpu_count.to_i.clamp(1..)
99+
effective = Crystal::System.effective_cpu_count.to_i.clamp(1..)
100+
# TODO: query for CPU limits (e.g. linux/cgroup, freebsd/rctl, ...)
101+
102+
Math.min(total, effective)
96103
end
97104

98105
# :nodoc:

0 commit comments

Comments
 (0)