Python 类中的方法如何多线程调用?

2018-04-24 20:58:07 +08:00
 wsds

这么写直接弹框报python运行出错,/尴尬,那这个怎么多线程调用getA/getB/getC/getD/getE呢?每次传参还要循环个arg2list列表


class ThreadTest():

    def __init__(self):
      pass

    def getA(self, args1, args2):
      pass
        
    def getB(self, args1, args2):
      pass

    def getC(self, args1, args2):
      pass

    def getD(self, args1, args2):
      pass

    def getE(self, args2):
      pass


if __name__ == "__main__":
    Test = ThreadTest()
    args2list = ['table1','table2']  
    args1 = 2
    thread_ = []
    for args2 in args2list:
        t1 = threading.Thread(target=Test.getA, args = (args1, args2))
        t2 = threading.Thread(target=Test.getB, args = (args1, args2))
        t3 = threading.Thread(target=Test.getE, args = (args2))
        t4 = threading.Thread(target=Test.getC, args = (args1, args2))
        t5 = threading.Thread(target=Test.getrace, args = (args1, args2))

        thread_.append(t1)
        thread_.append(t2)
        thread_.append(t3)
        thread_.append(t4)
        thread_.append(t5)
        print(thread_)

        for t in thread_:
            t.setDaemon(True)
            t.start()
        t.join()

3018 次点击
所在节点    Python
10 条回复
nitro123
2018-04-25 10:48:50 +08:00
pool.map ?
wsds
2018-04-25 10:51:08 +08:00
@nitro123 哪尼?
chenstack
2018-04-25 11:56:44 +08:00
wsds
2018-04-25 15:56:36 +08:00
@chenstack 我测试了一下,这样是挨个执行啊,没有并行执行啊,这是单线程吧
wsds
2018-04-25 16:04:30 +08:00
wsds
2018-04-25 16:10:33 +08:00
@chenstack 你的图是怎么回复的?
chenstack
2018-04-25 16:57:36 +08:00
把 t.join()注释后也许是你想要的效果。join 的作用是保证当前线程执行完成后,再执行其它线程。
回复图片直接贴网址就行
wsds
2018-04-25 17:48:43 +08:00
@chenstack 要把 t.setDaemon(True)也注释掉或者传为 False 才行,但感觉这不是一个完整的多线程了
chenstack
2018-04-25 19:09:14 +08:00
可以把 start 和 join 分开
for t in thread_:
t.setDaemon(True)
t.start()

for t in thread_:
t.join()

另外你一开始那样把 t.join()放在循环外面会出错大概是因为,有些线程设置为守护线程,但主线程退出后那些子线程还未结束。
wsds
2018-04-25 19:28:55 +08:00
@chenstack 分开确实可以。。。另外,我帖的只是些伪代码,实际当中还操作了数据库,主要报错原因是多线程查询 数据库报错,还没搞定,心塞_mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/449552

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX