Python multi-thread threading. Lock usage example

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.