開発環境
- 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 sys
import threading
threads = []
beers = 2000000
def error(msg):
print("{0}: {1}".format(msg, err), file=sys.stderr)
sys.exit(1)
def drink_lots():
global beers
for n in range(100000):
beers -= 1
print('壁にはビールが{0}本\n{0}本のビール'.format(beers))
for t in range(20):
thread = threading.Thread(target=drink_lots)
try:
thread.start()
except Exception as err:
error(err)
threads.append(thread)
for t in threads:
try:
t.join()
except Exception as err:
error(err)
print('現在、壁にはビールが{0}本あります。'.format(beers))
入出力結果(Terminal, IPython)
$ ./sample509.py 壁にはビールが2000000本 2000000本のビール 現在、壁にはビールが13494本あります。 $ ./sample509.py 壁にはビールが2000000本 2000000本のビール 現在、壁にはビールが221863本あります。 $ ./sample509.py 壁にはビールが2000000本 2000000本のビール 現在、壁にはビールが9411本あります。 $ ./sample509.py 壁にはビールが2000000本 2000000本のビール 現在、壁にはビールが63687本あります。 $ ./sample509.py 壁にはビールが2000000本 2000000本のビール 現在、壁にはビールが54700本あります。 $
0 コメント:
コメントを投稿