Python Multithreading Queue -
import threading queue import queue
print_lock = threading.lock() def job(worker): print_lock: open('messages.txt') f: 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 want each thread reads different messages,
your trying many things learn in same code snippet 1) multi-threading 2) queue data structure 3) thread synchronization mechanisms 4) locking etc.
let me answer regarding multi-threading only.
in case, every thread reading messages because target function "job"
opening file , reading data , every thread calling target function.
let me simplify stuff bit.
- you want read each line of file in new thread. so, instead of opening file in every thread , read it, open file 1 time , put data in list.
- now, every thread read 1 line list , print it. also, remove printed line list.
- once, data printed , still thread trying read, add exception.
code :
import threading import sys #global variable list 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 1 line list , print = file_data.pop() print except: #once data not present, let's print exception message print "------------------------" print "no data present in file" sys.exit() lock.release() #read data file , put list open("messages.txt") fh: file_data = fh.readlines() 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 --- great thread_0 --- how ? 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 : know sue of global
not recommended. learning purpose good.
Comments
Post a Comment