import threading
from queue import Queue
print_lock = threading.Lock()
def job(worker):
with print_lock:
with open('messages.txt') as f:
for line in f:
print(line)
def reader():
while True:
worker = q.get()
job(worker)
q.task_done()
q = Queue()
for x in range(10):
t = threading.Thread(target=reader)
t.daemon = True
t.start()
for worker in range(1):
q.put(worker)
q.join()
所以我想要的是每个线程读取不同的消息,
队列是线程安全的
所以,不需要线程锁
你尝试了太多的东西来学习相同的代码片段,比如 1( 多线程 2(队列数据结构 3( 线程同步机制 4( 锁定等
让我只回答多线程。
在您的情况下,每个线程都在读取所有消息,因为目标函数"job"
正在打开文件并读取所有数据,并且每个线程都在调用该目标函数。
让我简化一下东西。
- 您想在新线程中读取文件的每一行。 因此,我们不是在每个线程中打开文件并读取它,而是打开文件一次并将数据放入列表中。
- 现在,每个线程将从列表中读取一行并打印出来。此外,它将从列表中删除该打印行。
- 一旦打印了所有数据并且仍然线程尝试读取,我们将添加异常。
法典:
import threading
import sys
#Global variable list for reading file data
global file_data
file_data = []
#Create lock
lock = threading.Lock()
def reader():
while len(file_data) != 0:
print threading.currentThread().getName() + " --- "
try:
lock.acquire()
#Get one line from list and print it
a = file_data.pop()
print a
except:
#Once data is not present, let's print exception message
print "------------------------"
print "No data present in file"
sys.exit()
lock.release()
#Read data from file and put it into list
with open("messages.txt") as fh:
file_data = fh.readlines()
for x in range(2):
name = "Thread_"+str(x)
t = threading.Thread(name=name,target=reader)
t.start()
输出:
C:UsersdineshDesktop>python demo.py
Thread_0 --- Thread_1 ---
Each thread read each message
Thread_1 --- I am great
Thread_0 --- How Are you ?
Thread_1 --- Grey
Thread_0 --- Hey
Thread_1 --- Dinesh
Thread_0 --- Hello
------------------------
No data present in file
C:UsersdineshDesktop>
C:UsersdineshDesktop>
注意:我知道不建议起诉global
。但出于学习目的,这很好。