pythonは二つのスレッドを交互に実行することを実現します。


私は余計なことを言わないで、直接コードを見ましょう。

import threading
import time

def a():
  while True:
    lockb.acquire()
    print('a')
    locka.release()
    time.sleep(0.5)


def b():
  while True:
    locka.acquire()
    print('b')
    lockb.release()
    time.sleep(0.5)


if __name__ == "__main__":
  locka = threading.Lock()
  lockb = threading.Lock()

  ta = threading.Thread(None, a)
  tb = threading.Thread(None, b)

  locka.acquire()   #  a   

  ta.start()
  tb.start()
相手の鍵を取って、運転したら自分のロックを解除します。
補足知識:スレッド同期――2つのスレッドが交互にpythonを実行して実現する。
コードを見て!

import threading
import time
lockA=threading.Lock()
lockB=threading.Lock()
def printA(n):
 if n<0:
  return
 lockA.acquire()
 print("+++")
 lockB.release()
 time.sleep(0.1)
 printA(n-1)
def printB(n):
 if n<0: 
  return
 lockB.acquire()
 print("***")
 lockA.release()
 time.sleep(0.2)
 printB(n-1) 
 
lockB.acquire()
t1=threading.Thread(target=printA,args=(10,))
t2=threading.Thread(target=printB,args=(10,))
t1.start()
t2.start()
t1.join()
t2.join()
実習を探して、またオペレーティングシステムのものを思い出します。
アイデア:ロックロック2つとロックBを作成します。実行後は自分の鍵をロックし、相手の錠を解除します。
初期の場合、Aが先に作動するとAのロックを解除し、Bのロックをロックします。
以上のpythonは二つのスレッドを交互に実行することができます。つまり、小编は皆さんに全部の内容を共有します。