Haskell語言學習筆記(85)Async

安裝 async

$ cabal install async
async-2.2.1 installed

async / wait / concurrently

  • async :: IO a -> IO (Async a)
    啓動新線程,執行異步操做。
  • wait :: Async a -> IO a
    等待異步操做完成,並返回值。
  • concurrently :: IO a -> IO b -> IO (a, b)
    併發(concurrently)運行兩個 IO 操做,返回兩個結果。

示例

安裝 http-conduitgit

$ cabal install http-conduit
Installed http-conduit-2.3.2

Sample code to accompany the book "Parallel and Concurrent Programming in Haskell"github

module GetURL (getURL) where

import Network.HTTP.Conduit
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as L

getURL :: String -> IO ByteString
getURL url = L.toStrict <$> simpleHttp url

一個下載模塊 getURL併發

import GetURL

import Control.Concurrent.Async
import qualified Data.ByteString as B

main = do
  a1 <- async (getURL "http://www.wikipedia.org/wiki/Shovel")
  a2 <- async (getURL "http://www.wikipedia.org/wiki/Spade")
  r1 <- wait a1
  r2 <- wait a2
  print (B.length r1, B.length r2) -- (87653,58155)
  • 使用 async 開啓兩個線程同時下載兩個網頁。
  • 使用 await 等待下載結束並獲得結果。
import GetURL

import Control.Concurrent.Async
import qualified Data.ByteString as B

main = do
  (r1, r2) <- concurrently 
    (getURL "http://www.wikipedia.org/wiki/Shovel") 
    (getURL "http://www.wikipedia.org/wiki/Spade")
  print (B.length r1, B.length r2) -- (87653,58155)
  • 使用 concurrently 開啓兩個線程同時下載兩個網頁。下載結束時返回結果。
相關文章
相關標籤/搜索