Example of using python multi-thread threading. Lock

Source: Internet
Author: User
Tags mutex

Python locks can be extracted independently.

The code is as follows Copy Code

Mutex = Threading. Lock ()
Use of Locks

#创建锁
Mutex = Threading. Lock ()
#锁定
Mutex.acquire ([timeout])
#释放
Mutex.release ()

The locking method acquire can have an optional parameter timeout for a time-out period. If timeout is set, the return value can be used to determine if a lock has been obtained, allowing some other processing to be done.

The code is as follows Copy Code

#!/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

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.