How to call the second function while the first function is running, or vice versa?

Say I have two functions. It will take some time to complete one function, another simple and fast execution. I want to run both of them at the same time, but each of them works once in a row in a loop that ends after the completion of the first function. How can I do that?

## It will take a while to write out ##
function function_one()
 writedlm(big_array, "/very/large/file.csv") 
end

## trival function ##
function function_two()
 return 5
end

## I want to run something like this: ##
function call_both()
  while function_one()
    function_two()
  end
end

call_both()

I think I need to set up a parallel process here, but I don’t see how it should work.

+4
source share
1 answer

Here is a possible solution using the global variable (but const for the type):

const done_function_one = Ref{Bool}(false)

function call_both()
  done_function_one[] = false
  @sync begin
    @async begin
      function_one()
      done_function_one[] = true
    end
    @async begin
      while !done_function_one[]
        function_two()
      end
    end
  end
end

, - ( ). call_both , function_two, ( function_one).

+3

Source: https://habr.com/ru/post/1658258/


All Articles