Is there a mistake in this clojure solution for a sleeping hairdresser?

This is presented as a solution to the problem of a sleeping hairdresser . (Attributed to CGrand, but I found the link here )

yanked from cgrand

I'm interested in the dosync block in enter-the-shop . I understand that this is a transaction, therefore empty-seats will remain unchanged due to STM. However, is there a chance that send-off will be called multiple times if the transaction is retried? If not, then why, and if so, how can this be resolved?

UPDATE

Although the accepted answer is still correct, one thing I just noticed is the optimization that could be done - there is no reason to call send-off inside a transaction. It can be sent after receiving the return value of the transaction as follows:

 (if (dosync (when (pos? @empty-seats) (alter empty-seats dec))) (send-off barber cut-hair n) (debug "(s) turning away customer" n)) 

Interestingly, I realized this by working on the Haskell equivalent, which forces you to use different types for "agents" inside STM and outside of STM. The original solution above will not compile, since they must be either in a transaction or outside of any transaction. (My first reaction was to put them in a transaction until I realized that this was not necessary, and both of them could be extracted).

I think that a modified transaction should be excellent, because it closes the transaction faster, removes the variable from the transaction, and I think it is easier to read (there’s no need to even wonder about the possibility of sending it twice - which actually makes the whole question controversial). However, I will leave the question anyway for anyone who needs to know how STM and agents interact.

+4
source share
1 answer

Quoting clojure.org page for agents :

Agents are integrated with STM - any items made in a transaction are held until they are completed, and will be discarded if they are repeated or interrupted.

This way, send-off will only start once when the (/ if) transaction STM has completed successfully.

+5
source

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


All Articles