python学习(十三)进程和线程
python多进程
from multiprocessing import Process
import os def processFunc(name):
print("child process is %s, pid is %s" %(name, os.getpid() ) )
return
if __name__ == '__main__':
print("Parent process is %s." %(os.getpid() ))
p = Process(target = processFunc, args = ('test', ))
print('Child will start ')
p.start()
p.join()
print("Child stop")
进程池
from multiprocessing import Pool
import os , time, random def long_time_task(name):
print('run task name is %s' %(name))
start = time.time()
time.sleep(random.random()*3)
end = time.time()
print('Task %s runs %0.2f seconds.' %(name, (end - start )) ) if __name__ == '__main__':
print('Parent pid is %s' %(os.getpid() ))
p = Pool(4)
for i in range(5):
p.apply_async(long_time_task, args = (str(i) ,) )
print("Waiting all processes!!!")
p.close()
p.join()
print("All subprocess done")
启动进程,并调用命令行
import subprocess
print('$ nslookup www.python.org')
r = subprocess.call(['nslookup', 'www.python.org'])
print('Exit code:', r)
队列Queue可实现两个进程间通信
from multiprocessing import Process, Queue
import os, time, random def write(q):
print('Process to Write pid is %s' %(os.getpid() ) )
for i in ['A','B','C']:
q.put(i)
time.sleep(random.random()) def read(q):
print('Process to Read pid is %s' %(os.getpid() ) )
while(True):
value = q.get(True)
print('Get %s from queue ' %(value)) if __name__ == '__main__':
q = Queue()
pw = Process(target=write, args = (q,))
pr = Process(target = read , args = (q,) )
pw.start()
pr.start()
pw.join()
pr.terminate()
python多线程
import threading , time
def loop():
print('thread %s is running ...' % threading.current_thread().name)
n = 0
while n < 5:
n = n+ 1
print('thread %s >>> %s' %(threading.current_thread().name, n))
time.sleep(1)
print('thread %s ended. ' %(threading.current_thread().name ) ) if __name__ == '__main__':
print('Thread %s is running...' % threading.current_thread().name)
t = threading.Thread(target = loop, name = 'LoopThread')
t.start()
t.join()
print('Thread %s ended.' % threading.current_thread().name)
多线程访问全局变量,记得加锁
import time, threading # 假定这是你的银行存款:
balance = 0
lock = threading.Lock() def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n def run_thread(n):
for i in range(100000):
lock.acquire()
try:
change_it(n)
finally:
lock.release() t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
避免枷锁带来的效率衰退,可使用线程本地变量
import threading
# 创建全局ThreadLocal对象:
local_school = threading.local() def process_student():
# 获取当前线程关联的student:
std = local_school.student
print('Hello, %s in thread %s' %(std, threading.current_thread().name )) def process_thread(name):
# 绑定ThreadLocal的student:
local_school.student = name
process_student() if __name__ == '__main__':
t1 = threading.Thread(target = process_thread, args=('Alice',), name = 'Thread-A')
t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()
分布式进程,用于不同机器通信,采用BaseManager,在masterprocess.py中实现如下
import random, time, queue
from multiprocessing.managers import BaseManager task_queue = queue.Queue()
result_queue = queue.Queue() def taskqueuefunc():
global task_queue
return task_queue def resultqueuefunc():
global result_queue
return result_queue class QueueManager(BaseManager):
pass def ServerStart():
QueueManager.register('get_task_queue', callable = taskqueuefunc)
QueueManager.register('get_result_queue', callable = resultqueuefunc)
manager = QueueManager(address=('127.0.0.1', 5000), authkey=b'abc')
manager.start() task = manager.get_task_queue() result = manager.get_result_queue() for i in range(10):
n = random.randint(0,10000)
print('Put task %d...' %n)
task.put(n) # 从result队列读取结果:
print('Try get results...')
for i in range(10):
r = result.get(timeout=10)
print('Result: %s' % r)
# 关闭:
manager.shutdown()
print('master exit.') if __name__ == '__main__':
ServerStart()
在另一个文件workprocess.py中实现另一个进程处理数据
import time,sys,queue
from multiprocessing.managers import BaseManager class QueueManager(BaseManager):
pass QueueManager.register('get_task_queue')
QueueManager.register('get_result_queue') server_addr = '127.0.0.1'
print('Connect to server %s...' % server_addr)
m = QueueManager(address=(server_addr,5000),authkey=b'abc')
m.connect()
task = m.get_task_queue()
result = m.get_result_queue()
for i in range(10):
try:
n = task.get(timeout=1)
print('run task %d %d...' % (n,n))
r = '%d %d = %d' % (n,n,n*n)
time.sleep(1)
result.put(r)
except queue.Empty:
print('task queue is empty.')
print('worker exit.')
先启动masterprocess.py,然后启动workprocess.py,可以看到效果
谢谢关注我的公众号
python学习(十三)进程和线程的更多相关文章
- Python学习--17 进程和线程
线程是最小的执行单元,而进程由至少一个线程组成.如何调度进程和线程,完全由操作系统决定,程序自己不能决定什么时候执行,执行多长时间. 进程 fork调用 通过fork()系统调用,就可以生成一个子进程 ...
- Python学习--18 进程和线程
线程是最小的执行单元,而进程由至少一个线程组成.如何调度进程和线程,完全由操作系统决定,程序自己不能决定什么时候执行,执行多长时间. 进程 fork调用 通过fork()系统调用,就可以生成一个子进程 ...
- python学习之-- 进程 和 线程
python 进程/线程详解 进程定义:以一个整体的形式暴露给操作系统管理,它里面包含对各种资源的调用,内存的管理,网络接口的调用等等,对各种资源管理的集合,就可以叫做一个进程. 线程定义:线程是操作 ...
- day34 python学习 守护进程,线程,互斥锁,信号量,生产者消费者模型,
六 守护线程 无论是进程还是线程,都遵循:守护xxx会等待主xxx运行完毕后被销毁 需要强调的是:运行完毕并非终止运行 #1.对主进程来说,运行完毕指的是主进程代码运行完毕 #2.对主线程来说,运行完 ...
- python中的进程、线程(threading、multiprocessing、Queue、subprocess)
Python中的进程与线程 学习知识,我们不但要知其然,还是知其所以然.你做到了你就比别人NB. 我们先了解一下什么是进程和线程. 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CP ...
- Python学习day38-并发编程(线程)
figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...
- VC++学习之进程和线程的区别
VC++学习之进程和线程的区别 一.进程 进程是表示资源分配的基本单位,又是调度运行的基本单位.例如,用户运行自己的程序,系统就创建一个进程,并为它分配资源,包括各种表格.内存空间.磁盘 ...
- JUC学习笔记——进程与线程
JUC学习笔记--进程与线程 在本系列内容中我们会对JUC做一个系统的学习,本片将会介绍JUC的进程与线程部分 我们会分为以下几部分进行介绍: 进程与线程 并发与并行 同步与异步 线程详解 进程与线程 ...
- Python 中的进程、线程、协程、同步、异步、回调
进程和线程究竟是什么东西?传统网络服务模型是如何工作的?协程和线程的关系和区别有哪些?IO过程在什么时间发生? 一.上下文切换技术 简述 在进一步之前,让我们先回顾一下各种上下文切换技术. 不过首先说 ...
随机推荐
- Windows下遍历某目录下的文件
需求:要求遍历某个目录下的所有文件,文件夹 之前遇到过一些参考程序,其中有一种方法只能遍历 FAT32 格式的目录, 无法遍历NTFS的目录.
- Windows操作系统C盘占用空间过多
Windows操作系统C盘占用空间过多 大部分的windows电脑用户在长时间使用PC时都会遇到一个问题,就是C盘占用的空间会越来越多,乃至占满整个C盘. 后来在百度了一波,发现各种方法都试过了,也不 ...
- ip route ifconfig 基本命令
1.route命令 route –n route add –net 192.168.2.0/24 dev eth0 route add –net 192.168.2.0 netmask 255.255 ...
- Paper Reading - Convolutional Sequence to Sequence Learning ( CoRR 2017 ) ★
Link of the Paper: https://arxiv.org/abs/1705.03122 Motivation: Compared to recurrent layers, convol ...
- python基础-02-while格式化逻辑运算
python其他知识目录 1.循环打印“我是小马过河” while True: print('我是小马过河') #4.用while从一打印到10 #5.请通过循环,1 2 3 4 5 6 8 9 ...
- 《C》指针
储存单元: 不同类型的数据所占用的字节不同,上面一个长方形格子表示4个字节 变量: 变量的值,就是存储的内容.变量的名就相当于地址的名.根据变量类型分配空间:通过变量名引用变量的值,程序经过编译将变量 ...
- 解析DXF图形文件格式
一.DXF文件格式分析 DXF文件由标题段.表段.块段.实体段和文件结束段5部分组成,其内容如下. ☆标题段(HEADER)标题段记录AutoCAD系统的所有标题变量的当前值或当前状态.标题变量记录了 ...
- Apache 的知识点
apache 的官方文档 http://httpd.apache.org/docs/ Mac下如何查看Apache的版本 在终端(Terminal)中输入 apachectl -v,之后回车,结果如下 ...
- 【BioCode】读文件夹以发现缺失文件
代码说明: 使用单个蛋白质的txt计算PSSM生成的结果为单个的PSSM文件. 但是由于一些原因(如蛋白质序列过长),会导致一些蛋白质txt文件无法计算出pssm,为了找到这些没有计算出pssm的蛋白 ...
- 【week9】psp
本周psp 项目 内容 开始时间 结束时间 中断时间 净时间 2016/11/14 看论文 蛋白质甲基化位点预测 9:30 13:00 15 195 讨论班 组内讨论班 13:30 17:00 0 2 ...