[英]Python Multithreading Queue
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()
So what i want is each thread reads different messages,所以我想要的是每个线程读取不同的消息,
Queue is thread safe队列是线程安全的
so, threadling lock does not needed所以,不需要线程锁
your trying too many things to learn in same code snippet like 1) Multi-Threading 2) Queue Data Structure 3) Thread Synchronization Mechanisms 4) Locking etc.您尝试在同一代码片段中学习太多东西,例如 1) 多线程 2) 队列数据结构 3) 线程同步机制 4) 锁定等。
Let me answer regarding multi-threading only.让我只回答关于多线程的问题。
In your case, every thread is reading all messages because target function " job"
is opening file and reading all the data and every thread is calling that target function.在您的情况下,每个线程都在读取所有消息,因为目标函数“
job"
正在打开文件并读取所有数据,并且每个线程都在调用该目标函数。
Let me simplify the stuff bit.让我简化一下。
Code:代码:
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()
Output:输出:
C:\Users\dinesh\Desktop>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:\Users\dinesh\Desktop>
C:\Users\dinesh\Desktop>
NOTE: I know sue of global
is not recommended.注意:我知道不推荐使用
global
。 But for learning purpose it is good.但是为了学习目的,这是很好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.