在 STM 交易中使用跟踪是否安全?

Is it safe to use trace inside a STM stransaction?

我有一个交易由于某种原因无限期失败,我想在里面使用跟踪指令。例如,要在执行此片段中的事务之前打印 MVar 的状态:

    data_out <- atomically $ do 
        rtg_state <- takeTMVar ready_to_go 
        JobDescr hashid url <- T.readTBChan next_job_descr
        case rtg_state of 
            Ready_RTG n -> do
                putTMVar ready_to_go $ Processing_RTG n
                putTMVar start_harvester_browser hashid
                putTMVar next_test_url_to_check_chan  hashid
                putTMVar next_harvest_url hashid
                return (n,hashid,url)
            _ -> retry

这会使程序出现段错误或行为不当吗?

只要您使用 trace 仅用于调试目的,您应该没问题。作为一般规则,假设在您的程序的最终生产就绪版本中将没有 traces。

您永远不会观察到来自 trace 的段错误。它的 "unsafety" 源于它在纯代码中注入了可观察到的效果。例如,在 STM 中,当事务重试时,它的影响被假定为回滚。如果 trace 用于向用户发送消息,则无法回滚。如果 trace 的输出触发导弹发射,你将不得不处理国际副作用。如果 trace 只是用 "FYI, the code is doing X" 向开发人员发出信号,这不是程序核心逻辑的一部分,并且完全没问题。