Pythonã§æä»å¶å¾¡ã試ã
threadingã¢ã¸ã¥ã¼ã«ã«ã»ããã©ããããããªã
Lockã¨RLockã®éããSemaphoreã¨BoundedSemaphoreã®éããããããããªããåå¼·ä¸è¶³ã ã
http://docs.python.org/library/threading.html?highlight=threading#module-threading
# coding: utf-8 import threading class Plugin(threading.Thread): def __init__(self, fun): threading.Thread.__init__(self) self.fun = fun def run(self): self.fun() class ThreadGroup(object): # addã¡ã½ããã«é¢æ°ã渡ãããå ´å # Pluginã¯ã©ã¹ã«æ¸¡ãã¦å®è¡ # threading.Threadã®åå«ã¯ã©ã¹ãªãç´æ¥å®è¡ def __init__(self): self.lst = [] def add(self, obj): if isinstance(obj, type(lambda:1)): # if obj is function obj = Plugin(obj) self.lst.append(obj) obj.start() def joinall(self): for t in self.lst: t.join() def __len__(self): return len(self.lst) class UnsafeThread(threading.Thread): # æä»å¶å¾¡ãªã counter = 0 def __init__(self, no): threading.Thread.__init__(self) self.no = no def run(self): print "unsafe",self.no for i in range(1000): UnsafeThread.counter += 1 class SafeThread(threading.Thread): # ãã¥ã¼ããã¯ã¹ã«ããæä»å¶å¾¡ãã counter = 0 mutex = threading.Semaphore(1) def __init__(self, no): threading.Thread.__init__(self) self.no = no def run(self): SafeThread.mutex.acquire() for i in range(1000): SafeThread.counter += 1 SafeThread.mutex.release() # 4ã¤ã®ã¹ã¬ãããèµ°ããã¦joinãããã¨ã«ã¦ã³ã¿ã®å¤ãè¦ãã # 4000ã«ãªã£ã¦ããã¯ã # unsafe g = ThreadGroup() for i in range(4): g.add(UnsafeThread(i)) g.joinall() print UnsafeThread.counter # safe g = ThreadGroup() for i in range(4): g.add(SafeThread(i)) g.joinall() print SafeThread.counter
å®è¡çµæ
$ python th.py 4000 4000 $ python th.py 4000 4000 $ python th.py 3000 4000 $ python th.py 4000 4000 $ python th.py 3053 4000 $ python th.py 3318 4000 $ python th.py 4000 4000