5.1.15 the mutex of a thread

Source: Internet
Author: User
Tags mutex

 fromThreadingImportThread, LockImportTimen= 100deftask ():GlobalN#Mutex.acquire ()temp =N Time.sleep (0.1) n= Temp-1#mutex.release ()if __name__=='__main__':    #mutex = Lock ()t_l = []     forIinchRange (100): T= Thread (target=Task) T_l.append (t) t.start () forTinchT_l:t.join ()Print('Master', N)

Operation Result:

Main 99
View Code

A mutex is added:

#Mutex fromThreadingImportThread, LockImportTimen= 100deftask ():Globaln mutex.acquire () temp=N Time.sleep (0.1) n= Temp-1mutex.release ()if __name__=='__main__': Mutex=The difference between lock () # and child processes is that the child thread shares the memory space within the process, so there is no need to pass the lock to the thread. All threads within a process use the same lock.
# When the process is open, the data between the process and the subprocess is exclusive, so the data between the sub-processes is independent, and the lock is not the same lock. It is necessary to pass the lock to the child process to ensure that each child process uses the same lock. t_l= [] forIinchRange (100): T= Thread (target=Task) T_l.append (t) t.start () forTinchT_l:t.join ()Print('Master', N)

Operation Result:

Main 0
View Code

The role of mutexes: To turn parallel into serial.

5.1.15 the mutex of a thread

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.