0

は、誰もが、呼び出された関数のみならず、他の機能がロックされているように、ロックを取得する方法を知っていますスレッド。のPython:クロス機能が

関数a()、関数b()、関数c()を呼び出すと、関数b()& c()をロックしたいと思います。

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

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() 

は、どのように私は私が出力を与えるために上記のコードを望んでいた場合は、ロックを使用する必要がありますか?

感謝すべてのヘルプ、あなたが方法または別の使用あなたの機能の間で共有同じLockインスタンスでなければなりません Greetz

答えて

0

lock = threading.Lock() 

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

これは機能ごとに行い、出力します。

+0

ありがとうUnatiel、それはトリックをした! –