【发布时间】:2022-01-09 14:53:39
【问题描述】:
我有 4 个线程从 4 个文本文件中读取,另外还有一个线程来写入已经读取的 4 个线程,我使用了队列,那么如何使用信号量或互斥锁?
-
使用队列运行代码:
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)) -
我尝试通过互斥锁解决:
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()
【问题讨论】:
-
你做了什么尝试?与您的想法相反,StackOverflow 不是免费的编码服务。您应该提交honest attempt at the solution,然后然后仅在遇到问题时询问有关它的具体问题。 Stack Overflow 无意取代现有的教程或文档。
-
我从不认为 Stack 是免费代码,但我已经尝试过很多次以不同的方法解决问题,我感谢大家帮助我提出想法或帮助我编写代码,我是初学者编程。我将分享我解决问题的尝试
-
如果不出意外,你需要展示你的尝试——即使它不起作用——以证明你至少在自己解决程序方面付出了一些的努力。
-
@martineau 感谢您的澄清,我已经更新了
-
@martineau,它不像你叙述的那么直截了当。如果您输入“您尝试过什么?”作为评论,所以不会让你发布它。相反,您会收到此消息为红色。 评论不能包含该内容。如果作者没有展示尝试过的内容,您为什么认为他们尝试过任何东西?要么要求提供特定的信息,提出具体的改进建议,要么投反对票并继续前进。 这意味着提问者不必尝试任何事情,也不必证明它。
标签: python multithreading locking mutex python-multithreading