Reputation: 51
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:
The code run in pycharm generates this result:
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")
Upvotes: 4
Views: 837
Reputation: 42756
Threads don't gurantee that they will execute in any order, thats why you are getting different results on differents executions. So the threads are not dependant on IDE
Upvotes: 1