Python multi-thread lock two (one thread at a time acquires 2 locks)

Source: Internet
Author: User

#coding: Utf-8 ' thread lock ' import threadingimport timenum = 0  #全局变量num2  = 0def  runs ():     time.sleep (1)     global num # To make a change to a global variable inside a function, you need to declare     global num2    lock.acquire ()  # Locks during operation to prevent other threads from adding 1 to the NUM variable at the same time, ensuring that the data is at the same time ensured that only one thread makes changes to it, otherwise the data is incorrect     num += 1     lock.acquire ()   #再获得一把锁     num2 += 2      #在这里一个线程获得了2把锁, so need to release 2 times     lock.release ()   #  release 1th lock, add 1 after release lock, Only after releasing the next thread will start the operation of the NUM process, do not release the word otherwise will be occupied by the thread, causing the program to continue to execute, has been in a blocking state     time.sleep (0.01)      lock.release ()  #  release 2nd lock, add after 2 release lock     time.sleep (0.01)      print ("%s"  % num) lock = threading. Rlock ()   #RLock是允许同时获得好几把锁增加一把锁, if you only need a lock, then use threading. Lock () can # start 100 threads, which means these 100The thread runs the RUSN function at the same time For i in range ($):     t = threading. Thread (Target=runs,)     t.start ()


This article is from the "Operation and maintenance of AC Q Group: 223843163" blog, please be sure to keep this source http://freshair.blog.51cto.com/8272891/1898706

Python multi-thread lock two (one thread at a time acquires 2 locks)

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.