嵌套的dosync调用如何行为? [英] How do nested dosync calls behave?

查看:118
本文介绍了嵌套的dosync调用如何行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您创建嵌套的dosync调用时会发生什么?子事务将在父作用域中完成吗?如果父事务失败,这些子事务是否可逆?

What happens when you create nested dosync calls? Will sub-transactions be completed in the parent scope? Are these sub-transactions reversible if the parent transaction fails?

推荐答案

如果你的意思是语法嵌套,它取决于内部 dosync 是否会在与外部相同的线程上运行。

If you mean syntactic nesting, then the answer is it depends on whether the inner dosync will run on the same thread as the outer one.

在Clojure中,每当输入 dosync 块时,如果尚未在此线程上运行,则会启动一个新事务。这意味着当执行停留在单个线程上时,内部事务可以说被外部事务包含;但是如果 dosync 占用一个位置在语法上嵌套在另一个 dosync 中,而是恰好在一个新线程上启动,

In Clojure, whenever a dosync block is entered, a new transaction is started if one hasn't been running already on this thread. This means that while execution stays on a single thread, inner transactions can be said to be subsumed by outer transactions; however if a dosync occupies a position syntactically nested within another dosync, but happens to be launched on a new thread, it will have a new transaction to itself.

一个例子(希望)说明了发生了什么:

An example which (hopefully) illustrates what happens:

user> (def r (ref 0))
#'user/r
user> (dosync (future (dosync (Thread/sleep 50) (println :foo) (alter r inc)))
              (println :bar)
              (alter r inc))
:bar
:foo
:foo
1
user> @r
2

inner事务在打印后重试 :foo ; 外部事务从不需要重新启动。 (注意这之后, r 的历史链是增长的,所以如果大 dosync 评估第二次,内部 dosync 将不会重试,它仍然不会被合并到外部。)

The "inner" transaction retries after printing :foo; the "outer" transaction never needs to restart. (Note that after this happens, r's history chain is grown, so if the "large" dosync form were evaluated for a second time, the inner dosync would not retry. It still wouldn't be merged into the outer one, of course.)

顺便说一句,Mark Volkmann撰写了一篇关于Clojure的软件事务内存;它强烈建议读者有兴趣获得这种细节的坚实洞察。

Incidentally, Mark Volkmann has written a fantastic article on Clojure's Software Transactional Memory; it's highly recommended reading for anyone interested in gaining solid insight into details of this sort.

这篇关于嵌套的dosync调用如何行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆