-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcode11.py
More file actions
42 lines (29 loc) · 1.04 KB
/
code11.py
File metadata and controls
42 lines (29 loc) · 1.04 KB
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
42
# code11.py
import threading
# This class models a thread that blocks to a file
class MyThread(threading.Thread):
lock = threading.Lock()
def __init__(self, i, file):
super().__init__()
self.i = i
self.file = file
# This method is the one executed when the start() method is called.
def run(self):
# Blocks other threads from entering the next block
MyThread.lock.acquire()
try:
self.file.write('This line was written by thread #{}\n'.format(self.i))
finally:
# Releases the resource
MyThread.lock.release()
if __name__ == '__main__':
n_threads = 15
threads = []
# We create a file to write the output.
with open('out.txt', 'w') as file:
# All writing threads are created at once
for i in range(n_threads):
my_thread = MyThread(i, file)
# The thread is started, which executes the run() method.
my_thread.start()
threads.append(my_thread)