Skip to Content
Haskellによる並列・並行プログラミング
book

Haskellによる並列・並行プログラミング

by Simon Marlow, 山下 伸夫, 山本 和彦, 田中 英行
August 2014
Intermediate to advanced
328 pages
4h 36m
Japanese
O'Reilly Japan, Inc.
Content preview from Haskellによる並列・並行プログラミング

7章並行制御の基本: スレッドと MVar

並行制御の基本的な操作は、新しいスレッドを生成することです。並行Haskellにおいて、新しいスレッドを生み出すにはforkIOを使います。

forkIO :: IO () -> IO ThreadId

forkIOは引数としてIO ()型の計算を取ります。IO ()型の計算とはつまり、IOモナド内で最終的に()型の値へ評価される計算です。forkIOに渡された計算はシステム内の他のスレッドと並行に走る新しいスレッド内で実行されます。そのスレッドにエフェクトがあれば、それは他のスレッドのエフェクトと予測できない形で交錯します。

2つのスレッドを使う簡単な例で、エフェクトの交錯を説明しましょう。一方のスレッドは文字Aを繰り返し表示し、もう一方は文字Bを繰り返し表示します。

fork.hs

import Control.Concurrent
import Control.Monad
import System.IO

main = do
  hSetBuffering stdout NoBuffering            -- ①
  forkIO (replicateM_ 100000 (putChar 'A'))   -- ②
  replicateM_ 100000 (putChar 'B')            -- ③
  • ① 出力Handleをバッファリングなしのモードに設定し、エフェクトの交錯をよりはっきり見えるようにします。
  • ② スレッドを生成して文字Aを100,000回表示させます。
  • ③ メインスレッドで、文字Bを100,000回表示します。

このプログラム走らせてみると、出力は以下のようになるはずです。

AAAAAAAAABABABABABABABABABABABABABABABABABABABABABABAB ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

ベタープログラマ ―優れたプログラマになるための38の考え方とテクニック

ベタープログラマ ―優れたプログラマになるための38の考え方とテクニック

Pete Goodliffe, 柴田 芳樹
SVGエッセンシャルズ 第2版

SVGエッセンシャルズ 第2版

J. David Eisenberg, Amelia Bellamy-Royds, 原 隆文
アルゴリズムクイックリファレンス 第2版

アルゴリズムクイックリファレンス 第2版

George T. Heineman, Gary Pollice, Stanley Selkow, 黒川 利明, 黒川 洋
プログラミングRust

プログラミングRust

Jim Blandy, Jason Orendorff, 中田 秀基

Publisher Resources

ISBN: 9784873116891Other