PYTHON学习之路_PYTHON基础(10)
学习内容:
Python进程与线程
1、线程及线程类
2、线程守护
3、线程等待
4、线程锁
5、信号量
6、timer用法
7、队列
8、事件驱动
9、生产者消费者模型
10、进程及进程同步
11、进程池
12、递归锁
13、进程间通讯
一、线程及线程类
import threading
import time class MyThread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num def run(self):
print ('running on number :%s'%self.num)
print ('threading_act',threading.active_count() )
print ('threading_cur:',threading.current_thread())
time.sleep(3) if __name__ == '__main__':
t1 = MyThread('alex')
t2 = MyThread('json')
t1.start()
t2.start()
print (t1.getName())
print (t2.getName())
print('threading_c:', threading.current_thread())
二、线程守护
import threading
import time def run(n):
time.sleep(1)
print ("thread",n)
t_list = []
for i in range(10):
t = threading.Thread(target=run,args=(i,))
t.setDaemon(True)
t.start()
t_list.append(t)
print (t_list)
print ('----main thread----')
三、线程等待
import threading
import time
def run(n):
time.sleep(1)
print ("thread",n)
t_list = []
for i in range(10):
t = threading.Thread(target=run,args=(i,))
t.start()
t_list.append(t)
for t in t_list:
print ('t_list:',t)
t.join() #t.wait
print ('----main thread----')
四、线程锁
import threading
import time l = threading.Lock()
def run(n):
global num
l.acquire() #获取锁
num += 1
time.sleep(1)
l.release() #释放锁
print(num)
time.sleep(1)
#print("thread",n)
def run2():
count = 0
while num < 9:
print ('---------',count)
count += 1
num = 0
t_list = []
for i in range(10):
t = threading.Thread(target=run, args=(i,))
t.start()
t_list.append(t)
t2 = threading.Thread(target=run2)
t2.start()
for t in t_list:
t.join()
print("--main thread---")
print(num)
五、信号量(多线程)
import threading, time def run3(n):
semaphore.acquire()
time.sleep(1)
print('--------between run1 and run2-----',n)
semaphore.release()
if __name__ == '__main__':
num, num2 = 0, 0
semaphore = threading.BoundedSemaphore(5)
for i in range(20):
t = threading.Thread(target=run3,args=(i,))
t.start()
while threading.active_count() != 1:
pass
#print('active_count',threading.active_count())
else:
print('----all threads done---')
print(num, num2)
六、timer用法
import threading
import time
def hello():
print("hello, world")
t1 = time.time()
t = threading.Timer(3.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
t.join()
t2 = time.time()
change_time = t2 - t1
print (change_time)
七、队列
q = queue.Queue(maxsize=2)
# q.put(1)
# q.put(2)
# q.put(9)
# q.put('alex')
# q.put_nowait('jack')
# q.mutex
# q.qsize()
# q.join()
# q.task_done()
# q.empty() #判断队列是否为空
# q.full() #判断队列是否满
q=queue.LifoQueue()
q=queue.PriorityQueue()
q.put([4,'40'])
q.put([5,'50'])
q.put([1,'100'])
q.put([2,'20'])
print(q.get())
print(q.get())
print(q.get())
print(q.get())
八、事件驱动
import threading
import time
import random
def lighter():
count = 0
while True:
if count < 30:
if not event_flag.is_set():
event_flag.set()
print ('\033[32m----green light----\033[0m:%s'%count)
elif count < 35:
print('\033[33m----green light----\033[0m:%s' %count)
elif count < 60:
if event_flag.is_set():
event_flag.clear()
print('\033[31m----green light----\033[0m:%s' %count)
else:
count = 0
count += 1
time.sleep(0.2)
def car(n):
while True:
event_flag.wait()
print ('car [%s] is running throught the lighter...'%n)
time.sleep(random.randint(0, 3))
event_flag = threading.Event()
light_flag = threading.Thread(target=lighter)
light_flag.start()
car_list = ['宝马','大奔','路虎','兰博基尼','夏利']
for n in car_list:
car_flag = threading.Thread(target=car,args=(n,))
car_flag.start()
九、生产者消费者模型
import threading
import queue
import time
def consumer(name):
while True:
print ('%s 取到 骨头 【%s】,并吃了它。'%(name,q.get()))
time.sleep(0.5)
q.task_done() #回执
def producer(name):
count = 0
#while q.qsize() < 6:
for i in range (10):
print ('%s生成了骨头 %s!'%(name,count) )
q.put(count)
count +=1
time.sleep(0.3)
q.join()
q = queue.Queue(maxsize=5)
p = threading.Thread(target=producer,args=('Alex',))
p2 = threading.Thread(target=producer,args=('shuangmei',))
c = threading.Thread(target=consumer,args=('spider',))
p.start()
p2.start()
c.start()
十、进程及进程同步
from multiprocessing import Process, Lock
#作用:输出到屏幕出现乱行,加锁保证不串行 def f(l, i):
l.acquire()
try:
print('hello world', i)
finally:
l.release()
if __name__ == '__main__':
lock = Lock()
for num in range(10):
Process(target=f, args=(lock, num)).start()
十一、进程池
from multiprocessing import Process, Lock,Pool
import time
import os
#作用:输出到屏幕出现乱行,加锁保证不串行 def f(i):
#l.acquire()
print('hello world', i)
print ('-----f:',i,os.getpid())
time.sleep(4)
#l.release()
def callback(data):
print ('exec done---',data)
print('----callback',data,os.getpid()) if __name__ == '__main__':
lock = Lock()
pool = Pool(processes=5)
for num in range(10):
#Process(target=f, args=(lock, num)).start()
#pool.apply_async(func=f, args=(lock,num), callback=Bar)
pool.apply_async(func=f, args=(num,),callback=callback)
#apply 不要用,就用apply_async即可
pool.close()
pool.join()
十二、递归锁
import threading, time
def run1():
print("grab the first part data")
lock.acquire()
global num
num += 1
lock.release()
return num
def run2():
print("grab the second part data")
lock.acquire()
global num2
num2 += 1
lock.release()
return num2
def run3():
lock.acquire()
res = run1()
print('--------between run1 and run2-----')
res2 = run2()
lock.release()
print(res, res2)
if __name__ == '__main__':
num, num2 = 0, 0
lock = threading.RLock() #若用lock 则死锁
for i in range(10):
t = threading.Thread(target=run3)
t.start()
while threading.active_count() != 1:
print('active_count',threading.active_count())
else:
print('----all threads done---')
print(num, num2)
十三、进程间通讯
from multiprocessing import Process,Queue #进程的queue
import queue #线程的queue
def f(q):
q.put([42, None, 'hello'])
q.put(123)
if __name__ == '__main__':
#q=queue.Queue #线程的队列
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print(q.get()) # prints "[42, None, 'hello']"
print (q.get())
p.join()
PYTHON学习之路_PYTHON基础(10)的更多相关文章
- PYTHON学习之路_PYTHON基础(1)
学习内容: 1.Python介绍 2.Python程序初接触和变量 3.Python用户交互 4.Python数据类型 5.Python循环if...(elif)...else 6.Python循环w ...
- PYTHON学习之路_PYTHON基础(6)
学习内容: Python模块介绍 1.time &datetime模块 2.random 3.shutil 4.shelve 5.xml处理 6.configparser 7.hashlib ...
- PYTHON学习之路_PYTHON基础(4)
学习内容: 1.Python函数的基本语法 2.Python函数的返回值与变量 3.Python嵌套函数 4.Python递归函数及实例(二分查找) 5.Python匿名函数 6.Python内置方法 ...
- PYTHON学习之路_PYTHON基础(3)
学习内容: 1.Python字典 2.Python集合 3.Python字符编码 4.Python文件操作 5.Python实例 一.Python字典 1.定义: dic1={'name':'alex ...
- PYTHON学习之路_PYTHON基础(8)
学习内容: Python模块介绍 1.经典类 or 新式类 2.抽象接口 3.静态方法.类方法.属性方法 4.反射 5.异常处理 6.socket编程初识 7.用socket实现get.put文件等功 ...
- PYTHON学习之路_PYTHON基础(2)
学习内容: 1.Python数据类型与变量 2.Python字符串 3.Python列表 4.Python while循环 5.Python字典 6.Python实例 一.Python数据类型与变量 ...
- python学习之路-day2-pyth基础2
一. 模块初识 Python的强大之处在于他有非常丰富和强大的标准库和第三方库,第三方库存放位置:site-packages sys模块简介 导入模块 import sys 3 sys模 ...
- Python学习之路-Day2-Python基础2
Python学习之路第二天 学习内容: 1.模块初识 2.pyc是什么 3.python数据类型 4.数据运算 5.bytes/str之别 6.列表 7.元组 8.字典 9.字符串常用操作 1.模块初 ...
- Python学习之路-Day1-Python基础
学习python的过程: 在茫茫的编程语言中我选择了python,因为感觉python很强大,能用到很多领域.我自己也学过一些编程语言,比如:C,java,php,html,css等.但是我感觉自己都 ...
随机推荐
- JSP(include指令)页面
<%@ page language= "java" contentType="text/html;charset=UTF-8" %><html ...
- less预处理的好处,补充关于之前发表的rem单位的运用于计算
我认识的less 优点:优雅,好用,简单,可复用性强, 缺点:less并其实不能为我们减少沉余css代码,还是要靠自己的CSS基础去判断哪些是沉余代码或者是可以合并的代码 之前发表的一篇文章一看就懂得 ...
- JavaWeb---设置content-disposition响应头,让浏览器下载文件
package com.zyz; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServlet ...
- Linux下Git和GitHub使用方法总结
来源:Linux下Git和GitHub使用方法总结 1 Linux下Git和GitHub环境的搭建 第一步: 安装Git,使用命令 “sudo apt-get install git” 第二步: 到G ...
- qt5中QPrinter的使用兼容性问题
qt5与qt4在QPrinter中使用的不同点如下: 在.pro文件中加入如下语句:
- NGUI 多场景情况下 管理多个界面
简单的说就是在一个AllUI场景中,所有场景所需要的界面都挂在一个Empty GameObject下,然后这个Empty GameObject在代码中DontDestroyOnLoad,但是回到这个A ...
- hdu 5877 (dfs+树状数组) Weak Pair
题目:这里 题意: 给出一个n个结点的树和一个数k,每个结点都有一个权值,问有多少对点(u,v)满足u是v的祖先结点且二者的权值之积小于等于k. 从根结点开始dfs,假设搜的的点的权值是v,我们需要的 ...
- final
final的变量的值不能被改变.(包括形参) final的方法不能被重写. final的类不能被继承.
- RTP在。net中的使用(资料)
开源组件:lumisoft 网址:http://www.lumisoft.ee/lswww/download/downloads/Examples/ 非开源的免费组建:rtp.net (微软推荐)
- c# udp局域网通信
udp224.0.0.1 子网上的所有系统224.0.0.2 子网上的所有路由器224.0.0.12 dhcp服务器224.0.1.1 ntp224.0.1.24 wins服务器 http://www ...