Python multithreaded Threading. Lock Lock Usage Instance

Source: Internet
Author: User
The examples in this article describe Python multithreading threading. Lock lock usage examples, share to everyone for your reference. The specific analysis is as follows:

Python's locks can be extracted independently.

Copy the Code code as follows:

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


Locking method acquire can have an optional parameter of timeout time. If timeout is set, the return value after timeout can be used to determine if a lock has been obtained, allowing for some additional processing.

Copy the Code code 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

Hopefully this article will help you with Python programming.

  • 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.