Python implements alternate execution of two threads

I won't talk nonsense, just look at the code!

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()   #Ensure that a is executed first

 ta.start()
 tb.start()

Acquire the other party's lock and release your own lock after running

Supplementary knowledge: thread synchronization-two threads take turns to execute python implementation

Look at the code!

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

Looking for an internship, I have to remember the operating system again.

Idea: Create two locks lockA and lockB. After each execution, lock your own lock and release the other party's lock.

Initially, if A runs first, the lock of A is released and the lock of B is locked.

The above python implementation of two threads alternate execution is all the content shared by the editor, I hope to give you a reference.

Recommended Posts

Python implements alternate execution of two threads
Python implements horizontal stitching of pictures
Python implements the sum of fractional sequences
Two days of learning the basics of Python
Knowledge points of shell execution in python
7 features of Python3.9
Python implements the shuffling of the cards in Doudizhu
Python implements the source code of the snake game
[898] python get the intersection of two lists | union | difference
Python implements Super Mario
Python implements tic-tac-toe game
Python implements tic-tac-toe game
Python implements man-machine gobang
Python implements Tetris game
Python implements image stitching
Basics of Python syntax
Python implements minesweeper game
Python implements scanning tools
Basic syntax of Python
Basic knowledge of Python (1)
Prettytable module of python
09. Common modules of Python3
Python implements threshold regression
Python implements minesweeper games
Python implements electronic dictionary
Python implements guessing game