In fact, I run and debug these codes as below in both IDLE(Python 3.5.2 shell ) and Pycharm Community Edition 2017.2. But when I run the code many times, I found there are some questions confused me. The code run in pycharm generates this result:
- Thread-3 processing One Thread-1 processing Two Thread-3 processing Three Thread-2 processing Four Thread-3 processing Five Thread-1 processing Six Thread-2 processing Seven Thread-1 processing Eight
The code run in pycharm generates this result:
- Thread-1 processing One Thread-2 processing Two Thread-3 processing Three Thread-1 processing Four Thread-2 processing Five Thread-3 processing Six Thread-1 processing Seven Thread-2 processing Eight
As you can see, "1 3 2 3 1 2 1" and "2 3 1 2 3 1 2". I run many times and find this. So I just want to know, why the thread method is different in different IDE? And could you please tell me some good directions for learning thread in Python3?
import queue
import threading
import time
exitFlag = 0
class myThread(threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print("Open Thread:" + self.name)
process_data(self.name, self.q)
print("Exit Thread:" + self.name)
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
print("%s processing %s" % (threadName, data))
queueLock.release()
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
for tname in threadList:
thread = myThread(threadID, tname, workQueue)
thread.start()
threads.append(thread)
threadID += 1
queueLock.acquire()
for word in nameList:
#print(workQueue.empty())
workQueue.put(word)
#time.sleep(1)
queueLock.release()
while not workQueue.empty():
pass
exitFlag = 1
for t in threads:
t.join()
print("Exit Main Thread")