forked from The-Open-Source-Society/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Sleep_Sort.py
41 lines (32 loc) · 817 Bytes
/
Sleep_Sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import threading
import time
_lk = threading.Lock()
class SleepSortThread(threading.Thread):
def __init__(self, val):
self.val = val
threading.Thread.__init__(self)
def run(self):
global _lk
# Thread is made to sleep in proportion to value
time.sleep(self.val * 0.1)
# Acquire lock
_lk.acquire()
print(self.val, end = " ")
# Release lock
_lk.release()
def SleepSort(list):
ts = []
# Intialize a thread corresponding to each element in list
for i in list:
t = SleepSortThread(i)
ts.append(t)
# Start all Threads
for i in ts:
i.start()
# Wait for all threads to terminate
for i in ts:
i.join()
x = [2, 4, 3, 1, 6, 8, 4]
x = SleepSort(x)
# Output
# 1 2 3 4 4 6 8