セマフォが必要だと思います。次のサンプルコードを確認してください。
import threading
import datetime
class ThreadClass(threading.Thread):
def run(self):
now = datetime.datetime.now()
pool.acquire()
print "%s says hello, World! at time: %s" % (self.getName(),now)
pool.release()
pool = threading.BoundedSemaphore(value=1)
for i in range(10):
t = ThreadClass()
t.start()
この出力があります:
Thread-1 says hello, World! at time: 2013-05-20 18:57:47.609000
Thread-2 says hello, World! at time: 2013-05-20 18:57:47.609000
Thread-3 says hello, World! at time: 2013-05-20 18:57:47.609000
Thread-4 says hello, World! at time: 2013-05-20 18:57:47.609000
Thread-5 says hello, World! at time: 2013-05-20 18:57:47.609000
Thread-6 says hello, World! at time: 2013-05-20 18:57:47.609000
Thread-7 says hello, World! at time: 2013-05-20 18:57:47.609000
Thread-8 says hello, World! at time: 2013-05-20 18:57:47.609000
Thread-9 says hello, World! at time: 2013-05-20 18:57:47.609000
Thread-10 says hello, World! at time: 2013-05-20 18:57:47.609000
一方:
import threading
import datetime
class ThreadClass(threading.Thread):
def run(self):
now = datetime.datetime.now()
print "%s says hello, World! at time: %s" % (self.getName(),now)
for i in range(10):
t = ThreadClass()
t.start()
この出力があります:
Thread-1 says hello, World! at time: 2013-05-20 18:58:05.531000Thread-2 says hello, World! at time: 2013-05-20 18:58:05.
531000
Thread-4 says hello, World! at time: 2013-05-20 18:58:05.531000Thread-3 says hello, World! at time: 2013-05-20 18:58:05
.531000
Thread-6 says hello, World! at time: 2013-05-20 18:58:05.531000Thread-5 says hello, World! at time: 2013-05-20 18:58:05
.531000
Thread-8 says hello, World! at time: 2013-05-20 18:58:05.531000Thread-7 says hello, World! at time: 2013-05-20 18:58:05
.531000
Thread-10 says hello, World! at time: 2013-05-20 18:58:05.531000Thread-9 says hello, World! at time: 2013-05-20 18:58:0
5.531000
したがって、Python の BoundedSemaphore を使用すると、誰かがキューに書き込む前にセマフォが必要であることを確認できます。ただし、これは結果が正しい順序でキューに追加されることを保証するものではありません。
編集:
これを行い、注文を維持する場合は、次のようなものが必要になります。
import multiprocessing
import datetime
import random
import time
def funfun(number):
time.sleep(random.randint(0,10))
now = datetime.datetime.now()
return "%s says hello, World! at time: %s" % (number,now)
if __name__ == "__main__":
pool = multiprocessing.Pool(10)
for item in pool.imap(funfun,[i for i in range(10)]):
print item
これは次を印刷します:
0 says hello, World! at time: 2013-05-21 00:38:48.546000
1 says hello, World! at time: 2013-05-21 00:38:55.562000
2 says hello, World! at time: 2013-05-21 00:38:47.562000
3 says hello, World! at time: 2013-05-21 00:38:51.578000
4 says hello, World! at time: 2013-05-21 00:38:50.578000
5 says hello, World! at time: 2013-05-21 00:38:48.593000
6 says hello, World! at time: 2013-05-21 00:38:52.593000
7 says hello, World! at time: 2013-05-21 00:38:48.593000
8 says hello, World! at time: 2013-05-21 00:38:50.593000
9 says hello, World! at time: 2013-05-21 00:38:51.609000
したがって、これを使用すると、正しい順序でキューに追加することができ、ジョブは自分の番がキューに追加されるのを待ちます。