ERLANG wait() and blocking

2019-04-28 23:43发布

问题:

Does the following function block on its running core?

A great answer will detail the internal working of erlang and/or the cpu.

wait(Sec) -> 
    receive
    after (1000 * Sec) -> ok
    end.

回答1:

The process which executes that code will block, the scheduler which runs that process currently will not block. The code you posted is equal to a yield, but with a timeout.

The Erlang VM scheduler for that core will continue to execute other processes until that timeout fires and that process will be scheduled for execution again.



回答2:

Short answer: this will block only current (lightweight) process, and will not block all VM. For more details you must read about erlang scheduler. Nice description comes from book "Concurent Programming" by Francesco Cesarini and Simon Thompson.

...snip... When a process is dispatched, it is assigned a number of reductions† it is allowed to execute, a number which is reduced for every operation executed. As soon as the process enters a receive clause where none of the messages matches or its reduction count reaches zero, it is preempted. As long as BIFs are not being executed, this strategy results in a fair (but not equal) allocation of execution time among the processes. ...snip...



回答3:

nothing Erlang-specific, pretty classical problem: timeouts can only happen on a system clock interrupt. Same answer as above: that process is blocked waiting for the clock interrupt, everything else is working just fine.

There is another discussion about the actual time that process is going to wait which is not that precise exactly because it depends on the clock period (and that's system dependent) but that's another topic.



标签: erlang wait