Skip to content

Instantly share code, notes, and snippets.

@wgkoro
Created June 14, 2012 10:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wgkoro/2929493 to your computer and use it in GitHub Desktop.
Save wgkoro/2929493 to your computer and use it in GitHub Desktop.
Python スレッドの練習
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
スレッドの使い方練習
"""
import threading, time
import collections
import traceback
class Data:
def __init__(self):
self._stack = collections.deque()
for i in range(20):
self._stack.append(i)
print len(self._stack)
print self._stack
def get_one(self):
value = ''
if self._stack:
value = self._stack.popleft()
return value
class Worker(threading.Thread):
def __init__(self, v, list_data):
threading.Thread.__init__(self)
self._d = list_data
self.setName('T%s' % v)
self.kill = False
self.complete = False
def run(self):
self.get_elements()
def get_elements(self):
val = self._d.get_one()
while val or val is 0:
# Ctrl-C受けたらすっとばす
if not self.kill:
print '%s: %s' % (self.getName(), val)
val = self._d.get_one()
time.sleep(0.5)
else:
break
self.complete = True
print '%s: End Thread!' % self.getName()
def main(thread_count):
threads = []
data = Data()
# 指定された数だけスレッドを生成
for i in range(thread_count):
n = i+1
w = Worker(n, data)
threads.append(w)
w.start()
count = len(threads)
while count > 0:
try:
for t in threads:
if t is not None and t.isAlive():
t.join(1)
# これ忘れてて止まらなかった・・・
if t.complete:
count -= 1
except KeyboardInterrupt:
print 'Ctrl-C received!'
for t in threads:
t.kill = True
count = 0
except:
print traceback.format_exc()
count = 0
if __name__ == '__main__':
main(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment