zoukankan      html  css  js  c++  java
  • python自动化--语言基础线程、生产者消费者示例

    进程与线程的区别
    进程不共享空间,线程共享地址空间

    线程共享空间优缺点:
    优点:多线程给用户的体验好些,打开时占用的内存比进程少
    缺点:共享地址空间会相互干扰,甚至有影响

     1 import threading
     2 import time
     3 
     4 class Mythreading(threading.Thread):
     5     def __init__(self,threadID,name,counter):
     6         threading.Thread.__init__(self)    #固定格式
     7         self.threadID = threadID
     8         self.name = name
     9         self.counter = counter
    10         print("初始化完成")
    11     def run(self):                         #由cpu来处理决定线程间的执行顺序
    12         print("开始"+self.name)
    13         print_time(self.name,self.counter,5)
    14         print("结束"+self.name)
    15 
    16 def print_time(threasName,counter,delay):
    17     while counter:
    18         time.sleep(delay)
    19         print("%s:%s"%(threasName,time.ctime(time.time())))
    20         counter -= 1
    21 
    22 #创建线程
    23 thread1 = Mythreading(1,"thread1",1)
    24 thread2 = Mythreading(2,"thread2",2)
    25 
    26 #开启线程
    27 thread1.start()
    28 thread2.start()
     1 import threading
     2 import time
     3 
     4 class Mythreading(threading.Thread):
     5     def __init__(self,threadID,name,counter):
     6         threading.Thread.__init__(self)    #固定格式
     7         self.threadID = threadID
     8         self.name = name
     9         self.counter = counter
    10         print("初始化完成")
    11     def run(self):                         #由cpu来处理决定线程间的执行顺序
    12         threadLock.acquire()               #获得锁,成功获得锁定后返回True,可选的参数timeout不填时将一直阻塞直到获得锁定
    13         print_time(self.name,self.counter,3)
    14         threadLock.release()               #释放锁,开始下一个线程
    15 
    16 def print_time(threasName,counter,delay):
    17     while counter:
    18         time.sleep(delay)
    19         print("%s:%s"%(threasName,time.ctime(time.time())))
    20         counter -= 1
    21 
    22 threadLock = threading.Lock()
    23 threads = []
    24 
    25 #创建线程
    26 thread1 = Mythreading(1,"thread1",1)
    27 thread2 = Mythreading(2,"thread2",2)
    28 
    29 #开启线程
    30 thread1.start()
    31 thread2.start()
    32 
    33 # thread1.join()
    34 # thread2.join()
    35 threads.append(thread1)
    36 threads.append(thread2)
    37 for t in threads:
    38     t.join()       #后边的代码必须等待,等线程运行完成才会往后运行代码
    39 
    40 print("我的的花儿也谢了")

    为什么下图左为串行,下图右为并行运行呢?

    图左love启动后分别执行start和join,启动了join后边代码就需要等待前边代码运行完成。总共18s

    图右同时启动love和hate,运行所需要执行的时间然后停止。总共10s

     超级播放器示例,如下:

     1 import threading
     2 from time import sleep, ctime
     3 def music(func):
     4     for i in range(2):
     5         print ("I was listening to %s! %s" %(func,ctime()))
     6         sleep(4)
     7 def move(func):
     8     for i in range(2):
     9         print ("I was at the %s! %s" %(func,ctime()))
    10         sleep(5)
    11 
    12 def player(name):
    13     r = name.split('.')[1]
    14     if r=="mp3":
    15         music(name)
    16     elif r=="mp4":
    17         move(name)
    18     else:
    19         print("%s is error!"%name)
    20 
    21 lists = ["love.mp3","hate.mp4","cuicui.mp3","nnnn.mp4"]
    22 
    23 threads = []
    24 files = range(len(lists))
    25 for i in files:
    26     t = threading.Thread(target=player,args=(lists[i],))
    27     threads.append(t)
    28 
    29 if __name__ == '__main__':
    30     for i in files:
    31         threads[i].start()
    32     for i in files:
    33         threads[i].join()
    34     print ('all end: %s' %ctime())

    生产者与消费者示例:

     1 import threading
     2 class Produce(threading.Thread):
     3 
     4     def __init__(self,name):
     5         threading.Thread.__init__(self)
     6         self.name = name
     7     def run(self):
     8         global x
     9         tt.acquire()
    10         if x > 0 :
    11 
    12             print("我不生产了")
    13         else:
    14             for i in range(5):
    15                 x += 1
    16                 print("%s在生产中,第%d个"%(self.name,x))
    17         tt.release()
    18 
    19 class Consume(threading.Thread):
    20     def __init__(self,name):
    21         threading.Thread.__init__(self)
    22         self.name = name
    23     def run(self):
    24         global x
    25         tt.acquire()
    26         if x == 0:
    27 
    28             print("我不消费了")
    29         else:
    30             for i in range(5):
    31                 x -= 1
    32                 print("%s在消费中,第%d个"%(self.name,x+1))
    33         tt.release()
    34 x = 0
    35 tt = threading.Lock()
    36 # tt = threading.Condition
    37 
    38 p = Produce("produce")
    39 c = Consume("consume")
    40 
    41 p.start()
    42 c.start()
    43 
    44 p.join()
    45 c.join()
  • 相关阅读:
    Day10
    Python pyspider 安装与开发
    深入理解ES6之《块级作用域绑定》
    深入理解ES6之《扩展对象》
    这些特效对于学习前端我们很有用
    算法之旅 | 选择排序法
    JavaScript读取剪贴板中的表格生成图片
    深入理解ES6之《ES7》
    深入理解ES6之《用模块封装代码》
    php://input,$_POST,$HTTP_RAW_POST_DATA区别
  • 原文地址:https://www.cnblogs.com/hanxiaobei/p/6565610.html
Copyright © 2011-2022 走看看