【问题标题】:Python: cross-function threadingPython:跨函数线程
【发布时间】:2017-08-06 13:49:20
【问题描述】:

有没有人知道一种获取锁的方法,这样不仅被调用的函数而且其他函数都被锁定。

假设我有一堆函数( a(),b(),c() ),当我调用函数 a() 时,我还希望函数 b() 和 c() 被锁定。

import threading
from time import sleep

def a():
    for i in range(5):
        print(i)
        sleep(1)

def b():
    for i in range(5):
        print(i)
        sleep(1)

def c():
    for i in range(5):
        print(i)
        sleep(1)

thread_a=threading.Thread(target=a)
thread_a.start()
thread_b=threading.Thread(target=b)
thread_b.start()
thread_c=threading.Thread(target=c)
thread_c.start()

如果我希望上面的代码给出输出,我将如何使用锁:

0
1
2
3
4
0
1
2
3
4
0
1
2
3
4

?

任何帮助表示赞赏, 问候

【问题讨论】:

    标签: python multithreading python-2.7 python-3.x python-multithreading


    【解决方案1】:

    您必须以某种方式使用在您的函数之间共享的同一 Lock 实例。

    lock = threading.Lock()
    
    def a():
        with lock:
            for i in range(5):
                print(i)
                sleep(1)
    

    对每个函数都这样做,它会输出你想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多