简体   繁体   English

在类Python的方法中线程化两个函数

[英]Threading two functions inside a method of a class Python

I want to run 2 functions inside a method of a class at the same time in Python. 我想在Python中同时在类的方法中运行2个函数。 I tried to use threading module but it doesn't work. 我尝试使用threading模块,但无法正常工作。 My example codes are as below: 我的示例代码如下:

import os, sys
import threading
from threading import Thread

class Example():
    def __init__(self):
        self.method_1()

    def method_1(self):

        def run(self):
            threading.Thread(target = function_a(self)).start()
            threading.Thread(target = function_b(self)).start()

        def function_a(self):
            for i in range(10):
                print (1)

        def function_b(self):
            for i in range(10):
                print (2)

        run(self)


Example()

If above codes get executed, it will just print all 1 s first and then all 2 s. 如果执行了以上代码,它将仅先打印所有1 s,然后再打印所有2 s。 However, what I want is to print 1 and 2 at the same time. 但是,我要同时打印12 Thus, the desired output should be them mixed up. 因此,所需的输出应将它们混合在一起。

Is threading module capable to do that? threading模块能够做到这一点吗? If not, what module can do that? 如果没有,什么模块可以做到? If anyone knows how to solve it, please let me know. 如果有人知道如何解决,请告诉我。 Appreciated!! 感谢!

You need to pass the argument differently. 您需要以不同的方式传递参数。 Now you are actually executing your function in the threading.Thread initialisation call instead of creating a thread that executes the function. 现在,您实际上是在threading.Thread初始化调用中执行函数,而不是创建一个执行该函数的线程。

If something needs a function as a parameter, always use just function . 如果某些东西需要函数作为参数,请始终使用just function If you write function() , Python will not pass the actual function as a parameter, but executes the function on the spot and uses the return value instead. 如果编写function() ,Python不会将实际函数作为参数传递,而是当场执行该函数并改用返回值。

def run(self):
    threading.Thread(target = function_a, args=(self,)).start()
    threading.Thread(target = function_b, args=(self,)).start()

Here it is: 这里是:

import os, sys
import threading
from threading import Thread
import time

class Example():
    def __init__(self):
        self.method_1()

    def method_1(self):

        def run(self):
            threading.Thread(target = function_a, args = (self,)).start()
            threading.Thread(target = function_b, args = (self,)).start()

        def function_a(self):
            for i in range(10):
                print (1)
                time.sleep(0.01) # Add some delay here

        def function_b(self):
            for i in range(10):
                print (2)
                time.sleep(0.01) # and here


        run(self)


Example()

You will get outputs like this: 您将获得如下输出:

1
2
1
2
2
1
2
1
2
1
2
1
2
1
2
1
2
1
2
1

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

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