Skip to content

Instantly share code, notes, and snippets.

@hideaki-t
Created July 18, 2011 00:04
Show Gist options
  • Save hideaki-t/1088268 to your computer and use it in GitHub Desktop.
Save hideaki-t/1088268 to your computer and use it in GitHub Desktop.
sleepsort with barrier(python3.2+)
import threading
import time
import random
from sys import argv
from queue import Queue
class T(threading.Thread):
def __init__(self, num, barrier, queue):
self.barrier = barrier
self.num = num
self.queue = queue
threading.Thread.__init__(self)
def run(self):
self.barrier.wait()
time.sleep(self.num/100)
self.queue.put(self.num)
if __name__ == "__main__":
n = int(argv[1])
value_range = range(1, 100)
barrier = threading.Barrier(parties=n)
queue = Queue(n)
nums = [random.choice(value_range) for x in range(n)]
#nums = [random.randint(1, 100) for x in range(n)]
threads = [T(nums[x], barrier, queue) for x in range(n)]
#threads = [T(b, random.choice(value_range), q) for x in range(n)]
for t in threads:
t.start()
results = [queue.get() for x in range(n)]
print("orig.", nums)
print("sorted", results)
print("result", sorted(nums) == results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment