I have 4 thread that reading from 4 text files and additional thread to write that 4 threads already read , I used the Queue, So How I can use semaphore or mutex lock?
Code Run with Queue:
import queue import threading from datetime import datetime start_time = datetime.now() def print_text(q, filename): for line in open(filename, encoding="utf8"): q.put(line.strip()) q.put('--end--') def print_result(q, count=0): while count: line = q.get() if line == '--end--': count -= 1 else: print(line) if __name__ == "__main__": filenames = ['file_1.txt', 'file_2.txt', 'file_3.txt', 'file_4.txt'] q = queue.Queue() threads = [threading.Thread(target=print_text, args=(q, filename)) for filename in filenames] threads.append( threading.Thread(target=print_result, args=(q, len(filenames))) ) for thread in threads: thread.start() for thread in threads: thread.join() time_elapsed = datetime.now() - start_time print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))
My attempt to solved by Mutex Lock:
import threading import time import random mutex = threading.Lock() class thread_one(threading.Thread): def run(self): global mutex print ("The first thread is now sleeping") time.sleep(random.randint(1, 5)) print("First thread is finished") mutex.release() class thread_two(threading.Thread): def run(self): global mutex print ("The second thread is now sleeping") time.sleep(random.randint(1, 5)) mutex.acquire() print("Second thread is finished") class thread_three(threading.Thread): def run(self): global mutex print ("The Three thread is now sleeping") time.sleep(random.randint(1, 5)) mutex.acquire() print("Three thread is finished") class thread_four(threading.Thread): def run(self): global mutex print ("The Four thread is now sleeping") time.sleep(random.randint(1, 5)) mutex.acquire() print("Four thread is finished") mutex.acquire() t1 = thread_one() t2 = thread_two() t3 = thread_three() t4 = thread_four() t1.start() t2.start() t3.start() t4.start()
CodePudding user response:
import queue
import threading
s = threading.Semaphore(5)
def print_text(s, q, filenames):
with s:
for line in open(filenames, encoding="utf8"):
q.put(line.strip())
q.put('--end--')
def print_result(q, count=0):
while count:
line = q.get()
if line == '--end--':
count -= 1
else:
print(line)
if __name__ == "__main__":
filenames = ['file_1.txt', 'file_2.txt', 'file_3.txt', 'file_4.txt']
q = queue.Queue()
threads = [threading.Thread(target=print_text, args=(s, q, filename)) for filename in filenames]
threads.append( threading.Thread(target=print_result, args=(q, len(filenames))) )
for thread in threads:
thread.start()
for thread in threads:
thread.join()