zoukankan      html  css  js  c++  java
  • #并发的多线程效果演示#继承式多线程#守护线程 #互斥锁(用户自己的锁)

      

     1 #并发的多线程效果演示
     2 '''
     3 import threading
     4 
     5 def run(n):
     6     print ('task',n)
     7 
     8 t1 =threading.Thread(target=run,args=('t1',))
     9 t2 =threading.Thread(target=run,args=('t2',))
    10 
    11 t1.start()
    12 t2.start()
    13 '''
    14 
    15 '''
    16 import threading
    17 
    18 def run(n):
    19     print ('task',n)
    20 
    21 run('t1')
    22 
    23 run('t2')
    24 '''
    25 
    26 '''
    27 import threading
    28 import time
    29 def run(n):
    30     print ('task',n)
    31     time.sleep(2)
    32 
    33 t1 =threading.Thread(target=run,args=('t1',))
    34 
    35 t2 =threading.Thread(target=run,args=('t2',))
    36 
    37 run('t1')
    38 
    39 run('t2')
    40 
    41 '''
    42 
    43 
    44 import threading
    45 import time
    46 def run(n):
    47     print ('task',n)
    48     time.sleep(2)
    49 
    50 t1 =threading.Thread(target=run,args=('t1',))
    51 
    52 t2 =threading.Thread(target=run,args=('t2',))
    53 
    54 t1.start()
    55 
    56 t2.start()
    #并发的多线程效果演示
      1 #继承式多线程
      2 '''
      3 import threading
      4 import time
      5 
      6 class MYThread(threading.Thread):
      7     def __init__(self,n):
      8         super(MYThread,self).__init__()
      9         self.n = n
     10     def run(self):
     11         print ('runnint task',self.n)
     12 
     13 t1 =MYThread('t1')
     14 t2 =MYThread('t2')
     15 
     16 t1.start()
     17 t2.start()
     18 '''
     19 
     20 '''
     21 import threading
     22 import time
     23 
     24 def run(n):
     25     print ('task',n)
     26     time.sleep(2)
     27 
     28 t1 = threading.Thread(target=run,args=('t1',))
     29 t2 = threading.Thread(target=run,args=('t2',))
     30 
     31 t1.start()
     32 t2.start()
     33 
     34 '''
     35 
     36 '''
     37 import threading
     38 import time
     39 
     40 def run(n):
     41     print ('task',n)
     42     time.sleep(2)
     43 
     44 for i in range(50): 
     45 
     46     t = threading.Thread(target=run,args=('t-%s'% i ,))
     47     t.start()
     48  
     49 '''
     50 
     51 '''
     52 import threading
     53 import time
     54 #并行所以无法统计总共的时间
     55 def run(n):
     56     print ('task',n)
     57     time.sleep(2)
     58     print ('task done',n)
     59     
     60 start_time = time.time()
     61 for i in range(50): 
     62 
     63     t = threading.Thread(target=run,args=('t-%s'% i ,))
     64     t.start()
     65 
     66 print ('-------------all threads has finished...')
     67 print ('cost:',time.time() - start_time)
     68 
     69 '''
     70 '''
     71 import threading
     72 import time
     73 #设置等待全部子线程结束来测时间
     74 class MYThread(threading.Thread):
     75     def __init__(self,n,sleep_time):
     76         super(MYThread,self).__init__()
     77         self.n = n
     78 
     79         self.sleep_time = sleep_time
     80     def run(self):
     81         print ('runnint task',self.n)
     82         time.sleep(self.sleep_time)
     83         print ('task done,',self.n)
     84         
     85 t1 =MYThread('t1',2)
     86 t2 =MYThread('t2',4)
     87 
     88 t1.start()
     89 t2.start()
     90 
     91 t1.join()#等待
     92 t2.join()
     93 
     94 print ('main thread...')
     95 
     96 '''
     97 
     98 
     99 import threading
    100 import time
    101 #设置等待全部子线程结束来测时间
    102 def run(n):
    103     print ('task',n)
    104     time.sleep(2)
    105     print ('task done',n)
    106   
    107 start_time = time.time()
    108 t_objs = [] #储存线程实例
    109 for i in range(50): 
    110     t = threading.Thread(target=run,args=('t-%s'% i ,))
    111     t.start()
    112     t_objs.append(t)
    113 
    114 for t in t_objs:
    115     t.join()
    116 
    117 
    118 print ('-------------all threads has finished...')
    119 print ('cost:',time.time() - start_time)
    #继承式多线程

       

     1 #守护线程
     2 
     3 #主线程不在等待守护线程结束 就关闭程序
     4 
     5 import threading
     6 import time
     7 #设置等待全部子线程结束来测时间
     8 def run(n):
     9     print ('task',n)
    10     time.sleep(2)
    11     print ('task done',n,threading.current_thread())
    12   
    13 start_time = time.time()
    14 
    15 #t_objs = [] #储存线程实例
    16 
    17 for i in range(50): 
    18     t = threading.Thread(target=run,args=('t-%s'% i ,))
    19     t.setDaemon(True)#把当前先程设置为守护线程
    20     t.start()
    21     
    22     #t_objs.append(t)
    23 #for t in t_objs:
    24 #    t.join()
    25 
    26 
    27 print ('---all threads has finished...')
    28 print (threading.current_thread(),'当前线程数:',threading.active_count())
    29 print ('cost:',time.time() - start_time)
    #守护线程
     1 #互斥锁(用户自己的锁)
     2 #pyton 2.0不加锁上会出错 #pyton 3.0默认加锁,不会出错
     3 
     4 import threading
     5 import time
     6 
     7 def run(n):
     8     lock.acquire()
     9     global num
    10     num += 1
    11     #time.sleep(1) #没有释放 等于range(50)   50秒
    12     lock.release()
    13     
    14 lock = threading.Lock()
    15 num = 0
    16 
    17 t_objs = [] #储存线程实例
    18 
    19 for i in range(50): 
    20     t = threading.Thread(target=run,args=('t-%s'% i ,))
    21     t.start()
    22     t_objs.append(t)
    23     
    24 for t in t_objs:
    25     t.join()
    26 
    27 
    28 print ('---all threads has finished...')
    29 print (threading.current_thread(),'当前线程数:',threading.active_count())
    30 print ('num:',num)
    #互斥锁(用户自己的锁)

       

     1 #递归锁RLock(递归锁)
     2 
     3 #说白了就是在一个大锁中还要再包含子锁
     4 
     5 
     6 '''
     7 locks = {
     8         door1:key1,
     9         door2:key2
    10          }
    11 '''
    12 import threading,time
    13  
    14 def run1(): #平行房间门
    15     print("grab the first part data")
    16     lock.acquire()
    17     global num
    18     num += 1
    19     lock.release()
    20     return num
    21 def run2(): #平行房间门
    22     print("grab the second part data")
    23     lock.acquire()
    24     global  num2
    25     num2 += 1
    26     lock.release()
    27     return num2
    28 def run3():  #大门
    29     lock.acquire()
    30     res = run1()
    31     print('--------between run1 and run2-----')
    32     res2 = run2()
    33     lock.release()
    34     print(res,res2)
    35 '''
    36 if __name__ == '__main__':
    37  
    38     num,num2 = 0,0
    39     lock = threading.RLock()
    40     for i in range(10):
    41         t = threading.Thread(target=run3)
    42         t.start()
    43 
    44 '''
    45  
    46 num,num2 = 0,0
    47 lock = threading.RLock()
    48 #lock = threading.Lock()
    49 for i in range(10):
    50     t = threading.Thread(target=run3)
    51     t.start()
    52 
    53 while threading.active_count() != 1:
    54     print(threading.active_count())
    55 else:
    56     print('----all threads done---')
    57     print(num,num2)
    #递归锁RLock(递归锁)
     1 #Semaphore(信号量)
     2 '''
     3 互斥锁 同时只允许一个线程更改数据,
     4 而Semaphore是同时允许一定数量的线程更改数据 ,
     5 比如厕所有3个坑,那最多只允许3个人上厕所,
     6 后面的人只能等里面有人出来了才能再进去。
     7 '''
     8 
     9 import threading,time
    10  
    11 def run(n):
    12     semaphore.acquire()
    13     time.sleep(1)
    14     print("run the thread: %s
    " %n)
    15     semaphore.release()
    16  
    17 if __name__ == '__main__':
    18  
    19     #num = 0
    20     semaphore  = threading.BoundedSemaphore(5) #最多允许5个线程同时运行
    21     for i in range(22):
    22         t = threading.Thread(target=run,args=(i,))
    23         t.start()
    24         
    25  
    26 while threading.active_count() != 1:
    27     pass #print threading.active_count()
    28 else:
    29     print('----all threads done---')
    30     #print(num)
    #Semaphore(信号量)
      1 #Events  事件  全局变量
      2 
      3 #通过Event来实现两个或多个线程间的交互,下面是一个红绿灯的例子,
      4 #即起动一个线程做交通指挥灯,生成几个线程做车辆,车辆行驶按红灯停,绿灯行的规则。
      5 '''
      6 
      7 redLight = False
      8 while True:
      9     if counter > 30:
     10         redLight = True
     11 
     12     if counter > 50:
     13         redLight = False
     14         counter = 0
     15 
     16 '''
     17 '''
     18 #红绿灯
     19 import threading,time
     20 
     21 event = threading.Event()
     22 
     23 def lighter():
     24     count = 0
     25     
     26     while True:
     27         if count > 5 and count < 10 :#改成红灯
     28             event.clear()#把标志位置清空
     29             print('1mred light is on--红灯红灯红灯-')
     30         elif count >10 :   
     31             event.set()#改成绿灯
     32             count =0
     33         else:
     34             print('1mgeen light is on--绿灯绿灯绿灯-')    
     35         time.sleep(1)
     36         count += 1
     37 
     38 light = threading.Thread(target=lighter,)
     39 
     40 light.start()
     41 
     42 '''
     43 
     44 
     45 
     46 #红绿灯#车
     47 import threading,time
     48 
     49 event = threading.Event()
     50 
     51 def lighter():
     52     count = 0
     53     event.set() #先设置成绿灯
     54     while True:
     55         if count > 5 and count < 10 :#改成红灯
     56             event.clear()#把标志位置清空
     57             print('1mred light is on--红灯红灯红灯-')
     58         elif count >10 :   
     59             event.set()#改成绿灯
     60             count =0
     61         else:
     62             print('1mgeen light is on--绿灯绿灯绿灯-')    
     63         time.sleep(1)
     64         count += 1
     65 
     66 
     67 def car(name):
     68     while True:
     69         if event.is_set():#代表绿灯
     70             print ('[%s] running...'%name)
     71             time.sleep(1)
     72         else:
     73             print ('[%s] 看到红灯,等待……')
     74             event.wait()
     75             print ('[%s] 绿灯,开始……开车咯' % name)
     76                     
     77     
     78 light = threading.Thread(target=lighter,)
     79 light.start()
     80 
     81 car1 = threading.Thread(target=car,args=('Tesla',))
     82 car1.start()
     83 
     84 
     85 
     86 
     87 
     88 
     89 
     90 '''
     91 import threading,time
     92 import random
     93 def light():
     94     if not event.isSet():
     95         event.set() #wait就不阻塞 #绿灯状态
     96     count = 0
     97     while True:
     98         if count < 10:
     99             print('33[42;1m--green light on---33[0m')
    100         elif count <13:
    101             print('33[43;1m--yellow light on---33[0m')
    102         elif count <20:
    103             if event.isSet():
    104                 event.clear()
    105             print('33[41;1m--red light on---33[0m')
    106         else:
    107             count = 0
    108             event.set() #打开绿灯
    109         time.sleep(1)
    110         count +=1
    111 def car(n):
    112     while 1:
    113         time.sleep(random.randrange(10))
    114         if  event.isSet(): #绿灯
    115             print("car [%s] is running.." % n)
    116         else:
    117             print("car [%s] is waiting for the red light.." %n)
    118 if __name__ == '__main__':
    119     event = threading.Event()
    120     Light = threading.Thread(target=light)
    121     Light.start()
    122     for i in range(3):
    123         t = threading.Thread(target=car,args=(i,))
    124         t.start()
    125 
    126 
    127 
    128 
    129 #这里还有一个event使用的例子,员工进公司门要刷卡, 我们这里设置一个线程是“门”,
    130         #再设置几个线程为“员工”,员工看到门没打开,就刷卡,刷完卡,
    131         #门开了,员工就可以通过。
    132 
    133 
    134 #_*_coding:utf-8_*_
    135 __author__ = 'Alex Li'
    136 import threading
    137 import time
    138 import random
    139 
    140 def door():
    141     door_open_time_counter = 0
    142     while True:
    143         if door_swiping_event.is_set():
    144             print("33[32;1mdoor opening....33[0m")
    145             door_open_time_counter +=1
    146 
    147         else:
    148             print("33[31;1mdoor closed...., swipe to open.33[0m")
    149             door_open_time_counter = 0 #清空计时器
    150             door_swiping_event.wait()
    151 
    152 
    153         if door_open_time_counter > 3:#门开了已经3s了,该关了
    154             door_swiping_event.clear()
    155 
    156         time.sleep(0.5)
    157 
    158 
    159 def staff(n):
    160 
    161     print("staff [%s] is comming..." % n )
    162     while True:
    163         if door_swiping_event.is_set():
    164             print("33[34;1mdoor is opened, passing.....33[0m")
    165             break
    166         else:
    167             print("staff [%s] sees door got closed, swipping the card....." % n)
    168             print(door_swiping_event.set())
    169             door_swiping_event.set()
    170             print("after set ",door_swiping_event.set())
    171         time.sleep(0.5)
    172 door_swiping_event  = threading.Event() #设置事件
    173 
    174 
    175 door_thread = threading.Thread(target=door)
    176 door_thread.start()
    177 
    178 
    179 
    180 for i in range(5):
    181     p = threading.Thread(target=staff,args=(i,))
    182     time.sleep(random.randrange(3))
    183     p.start()
    184 
    185 
    186 
    187 
    188         
    189 '''
    190 
    191         
    #Events 事件 全局变量
  • 相关阅读:
    HDU4366 Successor 线段树+预处理
    POJ2823 Sliding Window 单调队列
    HDU寻找最大值 递推求连续区间
    UVA846 Steps 二分查找
    HDU3415 Max Sum of MaxKsubsequence 单调队列
    HDU时间挑战 树状数组
    UVA10168 Summation of Four Primes 哥德巴赫猜想
    UESTC我要长高 DP优化
    HDUChess 递推
    HDU4362 Dragon Ball DP+优化
  • 原文地址:https://www.cnblogs.com/ujq3/p/7345740.html
Copyright © 2011-2022 走看看