سؤال

If a Ruby method creates threads, but joins them within the method, is that still considered a side-effect from a functional programming perspective? The implementation I'm using is YARV Ruby, in which threads are created by the operating system, albeit with a GVL (Global VM Lock).

The reason the threads are being created is to do system calls, which is a side effect anyway, but I've never come across anyone saying whether threads are or aren't a side effect.

Simplified pseudo-code for this would look somewhat like the following:

  def run_tasks
    input_files = (1..4).map {|i| "input_#{i}"}
    output_files = (1..4).map {|i| "output_#{i}"}
    threads = [input_files, output_files].transpose.map |input_file, output_file|
      # system itself is a side effect
      Thread.new { system(["sub_program.rb", input_file, output_file]) }
    end
    threads.map(&:join)
  end
هل كانت مفيدة؟

المحلول

The passage of time is seldom considered a side-effect, so the use of threads to cause less time to take place is not a side-effect. This is analogous to the use of memoization to improve performance, which is also not a side-effect, even though it modifies hidden state.

Note that input_files.zip(output_files) will work as well as [input_files, output_files].transpose, and may communicate your intent better.

نصائح أخرى

If the threads aren't communicating in any way other than receiving initial parameters and returning some final result, or using any other side effects, then the use of threads can be considered pure.

If it would be possible to replace code saying "spawn a thread to run computation X and then get its result", with code that simply says "run computation X", with no effect other than changing the amount of runtime, then it's pure. If you can't do that, then the threads are doing something side-effecty.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top