This article mainly introduces python multi-thread threading. the usage of the Lock is analyzed in detail in the form of an instance. For more information about the usage of the python Lock, see the example in this article. an example of Lock usage is provided for your reference. The specific analysis is as follows:
Python locks can be extracted independently.
The code is as follows:
Mutex = threading. Lock ()
# Use of locks
# Create a lock
Mutex = threading. Lock ()
# Locking
Mutex. acquire ([timeout])
# Release
Mutex. release ()
The locking method acquire can have an optional timeout parameter timeout. If timeout is set, you can use the returned value to determine whether the lock is obtained after the timeout, so that you can perform other processing.
The code is as follows:
#! /Usr/bin/env python
# Coding = UTF-8
Import threading
Import time
Class MyThread (threading. Thread ):
Def run (self ):
Global num
Time. sleep (1)
If mutex. acquire (1 ):
Num = num + 1
Msg = self. name + 'set num to '+ str (num)
Print msg
Mutex. release ()
Num = 0
Mutex = threading. Lock ()
Def test ():
For I in range (5 ):
T = MyThread ()
T. start ()
If _ name _ = '_ main __':
Test ()
Thread-1 set num to 1
Thread-3 set num to 2
Thread-4 set num to 3
Thread-5 set num to 4
Thread-2 set num to 5
I hope this article will help you with Python programming.