Haskell中的并发:如果单线程但设置+ RTS -N会怎样

时间:2014-11-21 04:57:50

标签: haskell ghc haskell-platform

正如GHC文档所说,设置+RTS -N将使用多个线程来运行程序。如果我的程序是一个简单的单线程程序(即没有par,没有forkIO),如下所示,该怎么办?

m = 10^6

wr 0 = return ()
wr i = do  
        appendFile "/tmp/data.nothing" $ show(i)++"\n"
        wr (i-1)

main = do
    wr m
    putStrLn "done"

但是,当我使用-Ds(调试调度程序)标志运行程序时,我得到了以下日志

all threads:
threads on capability 0:
threads on capability 1:
    thread    7 @ 0x7fd5b0199000 is not blocked (TSO_DIRTY)
    thread 1944 @ 0x7fd592dc6390 is not blocked (TSO_DIRTY)
    thread 1945 @ 0x7fd592def8a8 is not blocked
    thread 1946 @ 0x7fd592dc6790 is not blocked
    thread 1947 @ 0x7fd592e0f790 is not blocked
    thread 1948 @ 0x7fd592df2420 is not blocked
    thread 1949 @ 0x7fd592df2000 is not blocked
    thread 1950 @ 0x7fd592e0f000 is not blocked
    thread 1951 @ 0x7fd592ddae90 is not blocked
    thread 1952 @ 0x7fd5b0156cc0 is not blocked
    thread 1953 @ 0x7fd5b2a2adc8 is not blocked
    thread 1954 @ 0x7fd5b2920568 is not blocked
    thread 1955 @ 0x7fd592c4b5a0 is not blocked
    thread 1956 @ 0x7fd5b289e7a8 is not blocked (TSO_DIRTY)
    thread 1957 @ 0x7fd592c4e160 is not blocked (TSO_DIRTY)
    thread 1958 @ 0x7fd592dc54a8 is not blocked (TSO_DIRTY)

我真的很想知道这些成千上万的线程在这里做了什么?

1 个答案:

答案 0 :(得分:8)

GHC线程和操作系统线程之间存在混淆。

“一个线程由一个TSO(线程状态对象)由GHC表示[...]线程由Capabilities运行,可以考虑由GHC管理的虚拟核心。功能又被映射到真正的操作系统线程或任务,虽然我们不会谈论它们。“

Inside 206-105 − The GHC scheduler

另见The Glasgow Haskell Compiler − The Scheduler

您实际需要的是功能。如果您使用+RTS -N1运行程序,则会看到只有一个功能,+RTS -N2等2个。

您可能还会注意到,即使您的程序本质上是单线程的,运行时系统也可以使用不同的线程来执行其他任务,例如垃圾收集器。