#Is it always bad for a process to block, even if it's in a separate task?

11 messages · Page 1 of 1 (latest)

hollow imp
#

For example: I have a process that streams audio over a websocket. It reads a file, and then sends chunks of audio one at a time with a Process.sleep in between each chunk to ensure the audio data is sent at the right speed:

def send_file(pid, path) do {:ok, data} = File.read(path) data |> Enum.chunk_every(@chunk_size) |> Enum.each(fn chunk -> WebSockex.send_frame(pid, chunk) Process.sleep(@delay_ms) end) end

I know that I could avoid the sleep by using e.g. Process.send_after. But I want to understand more generally if blocking like this is considered bad practice, and if so, why?

If I run the above code in a separate task, nothing else in my app will be blocked, so it seems like it shouldn't be a problem.

visual raft
#

It's not a problem, though I'd probably use a GenServer and send_after just so it could answer to system messages in order to be better visible in Observer and stuff.

#

w.r.t system scheduling, blocking like that is not an issue at all

hollow imp
#

Thanks. If this were inside a genserver (handle_call/handle_cast/handle_info), blocking would be bad right?

visual raft
#

well, it means that the process won't be handling any messages during that time. it's certainly unidiomatic

#

AFAIK some of the introspection stuff in Observer depends on servers answering to certain types of messages which it can't do if it's stuck in a sleep

hollow imp
#

How would I e.g. make a HTTP call inside a genserver?

visual raft
#

often people just do it. it won't break anything dramatic. there are some HTTP clients I think where you can get the result as a message instead of blocking waiting for it

#

I'm not entirely sure what part of the introspection uses the messages and wants the server to reply

#

of course you need to remember that the default timeout for a call is 5 seconds, so if your handle_call blocks longer, the caller will crash if the timeout isn't set to bigger

hollow imp
#

Makes sense, thanks