Python: Thread, multi-thread lock, multi-threaded recursive locks

Source: Internet
Author: User

#!usr/bin/env python
#-*-Coding:utf-8-*-

__author__ = "Samson"

Import Threading,time
def run (N):
Print ("task", N)
Time.sleep (2)
Print ("Current thread:", Threading.current_thread ()) #当前线程

T_obj = [] #存线程实例
Start_time = Time.time ()
For I in range (50):
t = Threading. Thread (target=run,args= ("t%s"%i,))
#t. Setdaemon (True) #把当前线程设置为守护线程, must be set before T.start () to function as the main thread will not wait for the child thread to end
T.start ()
T_obj.append (t)
Print ("Total thread:", Threading.active_count ()) #总线程数
For T in T_obj:
T.join () #等待线程执行完
Print ("%s"% (ABS (Start_time-time.time ())))

Multi-threaded lock
#!usr/bin/env python
#-*-Coding:utf-8-*-

__author__ = "Samson"

Import Threading,time
def run (N):
Lock.acquire () #锁上
Global num
num + = 1
#time. Sleep (1) #会变为单线程
Lock.release () #解锁
Lock = Threading. Lock () #创建锁
num = 0
T_obj = [] #存线程实例
For I in range (50):
t = Threading. Thread (target=run,args= ("t%s"%i,))
T.start ()
T_obj.append (t)
For T in T_obj:
T.join ()
Print ("%s"%num)
Multi-threaded recursive lock
#!usr/bin/env python
#-*-Coding:utf-8-*-

__author__ = "Samson"

Import Threading,time
def run ():
Lock.acquire () #锁上
res = RUN1 ()
Res2 = Run2 ()
Lock.release () #解锁
Def run1 ():
Lock.acquire () #锁上
Global num
num + = 1
Lock.release () #解锁
Def run2 ():
Lock.acquire () #锁上
Global num
num + = 1
Lock.release () #解锁
Lock = Threading. Rlock () #创建递归锁
num = 0
For I in range (10):
t = Threading. Thread (Target=run)
T.start ()
Print ("Now:", Threading.active_count ())
While Threading.active_count ()! = 1:
Print (Threading.active_count ())
Else
Print ("%s"%num)


Python: Thread, multi-thread lock, multi-threaded recursive 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.