首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在不同的多线程运行中获得不同的结果

在不同的多线程运行中获得不同的结果
EN

Stack Overflow用户
提问于 2013-10-07 07:54:30
回答 1查看 58关注 0票数 1

为什么当代码执行时,结果每次都不同?

我试图遵循代码是如何执行的,我感到困惑,我觉得这是没有意义的。

每次结果都是随机出现的

代码语言:javascript
运行
复制
#!/usr/bin/python

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 "Starting " + self.name
        process_data(self.name, self.q)
        print "Exiting " + self.name

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print "%s processing %s" % (threadName, data)
        else:
            queueLock.release()
        time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1

# Create new threads
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# Fill the queue
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()

# Wait for queue to empty
while not workQueue.empty():
    pass

# Notify threads it's time to exit
exitFlag = 1

# Wait for all threads to complete
for t in threads:
    t.join()
print "Exiting Main Thread"

代码源multithreading.htm

更新

抱歉,我是说结果的顺序

就像这样:

代码语言:javascript
运行
复制
Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-3 processing One
Thread-2 processing Two
Thread-1 processing Three
Thread-3 processing Four
Thread-2 processing Five
Exiting Thread-1
Exiting Thread-3
Exiting Thread-2
Exiting Main Thread
[Finished in 3.0s]

如果再试一次,结果

代码语言:javascript
运行
复制
Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-3 processing One
Thread-2 processing Two
Thread-1 processing Three
Thread-3 processing Four
Thread-3 processing Five
Exiting Thread-1
Exiting Thread-2
Exiting Thread-3
Exiting Main Thread
[Finished in 3.0s]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-07 08:00:10

我想,你所说的“结果”是指执行命令。多线程背后的一个想法是,除非您想要明确地指定执行顺序,否则您不必关心执行顺序。你完全依赖底层操作系统,系统负载,.等。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19219570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档