Skip to content

Instantly share code, notes, and snippets.

@yihuang
Created January 12, 2013 19:11
Show Gist options
  • Select an option

  • Save yihuang/4520000 to your computer and use it in GitHub Desktop.

Select an option

Save yihuang/4520000 to your computer and use it in GitHub Desktop.

Haskell微线程实现

用户线程与系统线程关系

  • 一对一 (传统线程实现)
  • 多对一 (gevent)
  • 一对多 (并行计算)
  • 多对多 (GHC, GO)

Good Performance

[https://gist.github.com/4045809]

  • 0.3s 创建10万条线程 10X faster than gevent
  • 10万条线程占用184M内存 3.2X less memory usage than gevent

基本情况

  • 抢占调度 (在内存分配时进行)
  • Chunked Stack (默认1k) * 自动增长 (生成指令检查堆栈空间) * 自动收缩 (GC)

主要数据结构

  • Thread State Object (TSO) * 堆栈和其他少量状态
  • HEC * Ownership Field, Lock * Message Queue * Run Queue of threads * Local allocation area * Foreign Out Call Thread Pool * ...

挑战1 - Blocked Foreign Call

  • A在调用前释放锁,并激活线程池中另一个系统线程B,或者创建新的。
  • A在调用返回时,通过消息队列通知B,并把自己加入线程池等待。

Simple To Use

timeout :: Int -> IO a -> IO (Maybe a)
timeout n io = do
    pid <- myThreadId
    timer <- forkIO $ do
        threadDelay n
        throwTo pid KillThread
    a <- io
    throwTo KillThread timerThread
    return (Just a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment