小编rya*_*025的帖子

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

我想在Python中同时在类的方法中运行2个函数。我尝试使用threading模块但它不起作用。我的示例代码如下:

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()
Run Code Online (Sandbox Code Playgroud)

如果执行上面的代码,它只会1先打印所有 s,然后打印所有2s。然而,我想要的是同时1打印。2因此,所需的输出应该是它们混合在一起。

threading模块有能力做到这一点吗?如果不能的话,什么模块可以做到这一点?如果有人知道如何解决,请告诉我。赞赏!

python multithreading class function multiprocess

1
推荐指数
1
解决办法
8905
查看次数

标签 统计

class ×1

function ×1

multiprocess ×1

multithreading ×1

python ×1