開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python 3.4 (プログラミング言語)
Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の12章(スレッド: 並列の世界)、ビールマグネット(p.509)をpythonで考えてみる。
ビールマグネット(p.509)
コード(BBEdit, Emacs)
sample509.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import threading beers = 2000000 def drinkLots(): global beers for x in range(100000): beers -= 1 threads = [threading.Thread(target=drinkLots) for x in range(20)] print('壁にはビールが{0}本\n{0}本のビール'.format( beers)) for thread in threads: thread.start() for thread in threads: thread.join() print('現在、壁にはビールが{0}本あります。'.format(beers))
入出力結果(Terminal, IPython)
$ ./sample509.py 壁にはビールが2000000本 2000000本のビール 現在、壁にはビールが1118479本あります。 $ ./sample509.py 壁にはビールが2000000本 2000000本のビール 現在、壁にはビールが965046本あります。 $
0 コメント:
コメントを投稿