IDLE和pycharm中的python线程方法是不同的吗?

时间:2017-09-15 06:20:29

标签: python multithreading

事实上,我在IDLE(Python 3.5.2 shell)和Pycharm Community Edition 2017中运行和调试这些代码如下所示。 但是当我多次运行代码时,我发现有些问题让我很困惑。在pycharm中运行的代码会生成以下结果:

  • Thread-3处理一 Thread-1处理二 Thread-3处理三 线程-2处理四 Thread-3处理五 Thread-1处理六 Thread-2处理七 Thread-1处理八

在pycharm中运行的代码会生成以下结果:

  • 线程-1处理一 Thread-2处理二 Thread-3处理三 Thread-1处理四 线程-2处理五 Thread-3处理六 Thread-1处理七 Thread-2处理八

正如您所见," 1 3 2 3 1 2 1"和" 2 3 1 2 3 1 2"。我跑了很多次才发现这个。所以我只想知道,为什么线程方法在不同的IDE中有所不同?您能否告诉我在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")

1 个答案:

答案 0 :(得分:1)

线程不保证他们将以任何顺序执行,这就是为什么你会在不同的执行中得到不同的结果。 所以线程不依赖于IDE