简体   繁体   English

同一程序在线程模块中输出不同的输出

[英]same program different output in threading module

start.py code is as below. start.py代码如下。

import threading
class myThread(threading.Thread):
        def __init__(self, threadID, name):
                threading.Thread.__init__(self)
                self.threadID = threadID
                self.name = name

        def run(self):
                currentThreadname = threading.currentThread()
                print "running in ", currentThreadname

thread = myThread(1,"mythrd")
thread.start()

Start it with python for two times. 用python启动它两次。

python start.py
running in  <myThread(mythrd, started 140461133485824)>
python start.py
running in  <myThread(mythrd, started 140122860668672)>

run.py code is as below. run.py代码如下。

import threading
class myThread(threading.Thread):
        def __init__(self, threadID, name):
                threading.Thread.__init__(self)
                self.threadID = threadID
                self.name = name

        def run(self):
                currentThreadname = threading.currentThread()
                print "running in ", currentThreadname

thread = myThread(1,"mythrd")
thread.run()

run.py is only one line different from start.py. run.py只有一行不同于start.py。
Now start run.py for two times. 现在启动run.py两次。

python  run.py
running in  <_MainThread(MainThread, started 139854546364160)>
python  run.py
running in  <_MainThread(MainThread, started 139854546364160)>

startandrun.py code is as below. startandrun.py代码如下。

class myThread(threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name

    def run(self):
        currentThreadname = threading.currentThread()
        print "running in ", currentThreadname

thread = myThread(1,"mythrd")
thread.start()
thread.run()

Now start startandrun.py for two times also. 现在也开始startandrun.py两次。

python  startandrun.py
running in  <myThread(mythrd, started 140317119899392)>
running in  <_MainThread(MainThread, started 140317144454912)>
python  startandrun.py
running in running in  <_MainThread(MainThread, started 139980210505472)>
 <myThread(mythrd, started 139980185949952)>

As JohanL say: 正如JohanL所说:
When running two separate threads, all bets are off as to which will execute first. 当运行两个单独的线程时,所有的注意都将关闭,因为它将首先执行。
You are basically leaving the scheduling to the operating system. 您基本上将调度留给操作系统。 The first time to execute startandrun.py, thread.start() was executed before thread.run() ,it result in the output: 第一次执行startandrun.py时, thread.start()thread.run()之前执行,它导致输出:

running in  <myThread(mythrd, started 140317119899392)>
running in  <_MainThread(MainThread, started 140317144454912)>

The second time to execute startandrun.py, thread.start() was executed after thread.run() ,why not result in the output: 第二次执行startandrun.py, thread.start()thread.run()之后执行,为什么不导致输出:

running in  <_MainThread(MainThread, started 140317144454912)>
running in  <myThread(mythrd, started 140317119899392)>

instead of 代替

running in running in  <_MainThread(MainThread, started 139980210505472)>
 <myThread(mythrd, started 139980185949952)>

This is happening because of the way you are printing the values: 这是因为您打印值的方式:

print "running in ", currentThreadname

Adding a comma is similar to: 添加逗号类似于:

print 'running in ' # without new line at the end
print currentThreadname

And since the two functions are running at the same time here is how the order is executed: 由于这两个函数同时运行,因此订单的执行方式如下:

print 'running in ' # without new line FUNCTION #1
print 'running in ' # without new line FUNCTION #2
print currentThreadName # with new line at the end FUNCTION #1
print currentThreadName # with new line at the end FUNCTION #2

Try using one print statement without commas to understand how it should be: 尝试使用一个没有逗号的print语句来理解它应该是什么:

def run(self):
    currentThreadname = threading.currentThread()
    print "running in {}".format(currentThreadname)

This will behave normally but since the two functions are printing at the same time, you might get the following output: 这将表现正常,但由于这两个函数同时打印,您可能会得到以下输出:

running in <myThread(mythrd, started 10716)>running in <_MainThread(MainThread, started 12132)>

So to prove that this will work you can use a delay in between the two calls using time.sleep() : 因此,要证明这将起作用,您可以使用time.sleep()在两次调用之间使用延迟:

import threading
import time

class myThread(threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name

    def run(self):
        currentThreadname = threading.currentThread()
        print "running in {}".format(currentThreadname)

thread = myThread(1,"mythrd")
thread.start()
time.sleep(0.1)
thread.run()

Now you can see that you get your desired output because each function is printing one time with a 0.1 sec delay in between the calls: 现在你可以看到你得到了你想要的输出,因为每个函数都打印一次,在两次调用之间延迟0.1秒:

running in <myThread(mythrd, started 5600)>
running in <_MainThread(MainThread, started 7716)>

EDIT: 编辑:

Your issue is exactly why you should use multithreading instead of running the same thread twice. 您的问题正是为什么您应该使用多线程而不是两次运行相同的线程。 When you use multithreading You can use thread.join() which will wait for the thread to finish off and then continue the code, or you can use threading.lock() so you can continue your code but lock a function to be used by one thread at a time. 当你使用多线程你可以使用thread.join() ,它将等待线程完成然后继续代码,或者你可以使用threading.lock()这样你可以继续你的代码,但锁定一个函数使用一次一个线程。 Here are some examples: 这里有些例子:

thread.join() : thread.join()

thread = myThread(1, "mythrd")
thread2 = myThread(2, "thrd2")
thread.start()
thread.join() # code will stop here and wait for thread to finish then continue
thread2.run()

threading.lock() : threading.lock()

....
    def run(self):
        with lock: # if one thread uses this lock the other threads have to wait
            currentThreadname = threading.currentThread()
            print "running in ", currentThreadname

thread = myThread(1, "mythrd")
thread2 = myThread(2, "thrd2")
lock = threading.Lock()
thread.start() 
thread2.run()
# code keeps running even if there are threads waiting for the lock

So, all you want is to synchronize your threads. 所以,你想要的只是同步你的线程。 It can be done easily using the join() function in threading library. 可以使用线程库中的join()函数轻松完成。

You can do something like this 你可以做这样的事情

class myThread(threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name

    def run(self):
        currentThreadname = threading.currentThread()
        print "running in ", currentThreadname

thread = myThread(1,"mythrd")
t1 =  thread.start()
t1.join()
t2 =  thread.run()
t2.join()

You can also use semaphore and Lock for better reasons. 您还可以使用信号量和锁定以获得更好的理由。 See the docs for more detail. 有关更多详细信息,请参阅文档。

Probably you do not understand how threads are working. 可能你不明白线程是如何工作的。 Read this carefully. 阅读仔细。

I highly suggest you to use ThreadPoolExecutor from the futures library. 我强烈建议您使用futures库中的ThreadPoolExecutor

What version python were you using? 你用的是什么版本的python? In python 2, "print" is not thread safe. 在python 2中,“print”不是线程安全的。 Please see http://tech.queryhome.com/54593/is-print-thread-safe-in-python-2-6-2-7 . 请参阅http://tech.queryhome.com/54593/is-print-thread-safe-in-python-2-6-2-7

If threads switch during "print", the outputs are mixed, like what you saw. 如果线程在“打印”期间切换,则输出会混合,就像您看到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM