python学习日志--day9
来源:互联网 发布:阿里巴巴菜鸟网络待遇 编辑:程序博客网 时间:2024/05/18 03:38
一、进程与线程
1、定义:
- 进程是具有一定独立功能的程序关于某个数据集合上的一次运行活动。(进程就是各种资源的集合)
- 线程是操作系统能够进行运算调度的最小单位,是一串指令的集合。它被包含在进程之中,是你进程中的实际运作单位。一条进程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
2、区别
- Threads share the address space of the process that created it; processes have their own address space.
- Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
- Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
- New threads are easily created; new processes require duplication of the parent process.
- Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
- Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.
3.示例
直接调用
import threading,timedef run(n): print("task",n) time.sleep(2)t1 = threading.Thread(target=run,args=("t1",))t2 = threading.Thread(target=run,args=("t2",))t1.start()t2.start()
输出结果
继承式调用
import threadingclass MyThread(threading.Thread): def __init__(self,n): super(MyThread,self).__init__() self.n = n def run(self): print("run task",self.n)t1 = MyThread("t1")t2 = MyThread("t2")t1.start()t2.start()
输出结果
线程串行
import threading,timedef run(n): print("task",n) time.sleep(2)t1 = threading.Thread(target=run,args=("t1",))t2 = threading.Thread(target=run,args=("t2",))t1.start()t1.join() #程序执行后,先运行t1,sleep(2)之后执行t2 (=wait())t2.start()
4、主线程和子线程
5、线程锁(互斥锁)
import timeimport threadingdef addNum(): global num #在每个线程中都获取这个全局变量 print('--get num:',num ) time.sleep(1) num -=1 #对此公共变量进行-1操作num = 10 #设定一个共享变量thread_list = []for i in range(10): t = threading.Thread(target=addNum) t.start() thread_list.append(t)for t in thread_list: #等待所有线程执行完毕 t.join()print('final num:', num )输出结果
6/
加锁
import timeimport threading def addNum(): global num #在每个线程中都获取这个全局变量 print('--get num:',num ) time.sleep(1) lock.acquire() #修改数据前加锁 num -=1 #对此公共变量进行-1操作 lock.release() #修改后释放 num = 100 #设定一个共享变量thread_list = []lock = threading.Lock() #生成全局锁for i in range(100): t = threading.Thread(target=addNum) t.start() thread_list.append(t) for t in thread_list: #等待所有线程执行完毕 t.join() print('final num:', num )
6、信号量(互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据)
import threading, timedef run(n): semaphore.acquire() time.sleep(1) print("run the thread: %s\n" % n) semaphore.release()if __name__ == '__main__': semaphore = threading.BoundedSemaphore(5) # 最多允许5个线程同时运行 for i in range(8): t = threading.Thread(target=run, args=(i,)) t.start()while threading.active_count() != 1: pass # print threading.active_count()else: print('----all threads done---') #print(num)
7、even(通过Event来实现两个或多个线程间的交互)
- even.set()
- even.wait()
- even.clear()
红绿灯程序
import timeimport threadingevent = threading.Event()def lighter(): count = 0 event.set() #先设置绿灯 while True: if count >5 and count < 10: #改成红灯 event.clear() #把标志位清了 print("\033[41;1mred light is on....\033[0m") elif count >10: event.set() #变绿灯 count = 0 else: print("\033[42;1mgreen light is on....\033[0m") time.sleep(1) count +=1def car(name): while True: if event.is_set(): #代表绿灯 print("[%s] running..."% name ) time.sleep(1) else: print("[%s] sees red light , waiting...." %name) event.wait() print("\033[34;1m[%s] green light is on, start going...\033[0m" %name)light = threading.Thread(target=lighter,)light.start()car1 = threading.Thread(target=car,args=("Tesla",))car1.start()
8、queue队列
9、生产者消费者模型(通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度)
import threading,timeimport queueq = queue.Queue(maxsize=10)def Producer(name): count = 1 while True: q.put("骨头%s" % count) print("生产了骨头",count) count +=1 time.sleep(0.1)def Consumer(name): #while q.qsize()>0: while True: print("[%s] 取到[%s] 并且吃了它..." %(name, q.get())) time.sleep(1)p = threading.Thread(target=Producer,args=("Alex",))c = threading.Thread(target=Consumer,args=("ChengRonghua",))c1 = threading.Thread(target=Consumer,args=("王森",))p.start()c.start()c1.start()
阅读全文
0 0
- python学习日志--day9
- python学习-Day9-练习题复习
- Day9、Python
- Python-day9
- 暑期工作日志-Day9
- Python的学习笔记DAY9---Django学习1
- python day9(20170302 )
- Python--day9 文件练习题
- 传智播客学习日记Day9
- java学习笔记day9
- Android学习笔记day9
- java学习day9
- Java学习--day9-partone
- Java学习--day9-parttwo
- python自动化之路-day9
- Python Day9 :一个小练习
- 机器学习学习笔记.day9
- day9
- 比特币及钱包的基础知识
- 匿名内部类 的参数
- MySQL---常见函数
- 好用的Markdown编辑器一览
- UVA 1093 Castles
- python学习日志--day9
- 牛客网---2016---华为最高分是多少
- RESTful API 设计指南
- 不以应用为目的的区块链项目都是耍流氓
- spring四天计划(4day)
- 填报流水号,缺省表达式设置
- 【SCU】Carries
- CSS学习笔记(Day4)
- Connection timed out: connect. If you are behind an HTTP proxy, please configure the proxy