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学习(十三)进程和线程的更多相关文章

  1. Python学习--17 进程和线程

    线程是最小的执行单元,而进程由至少一个线程组成.如何调度进程和线程,完全由操作系统决定,程序自己不能决定什么时候执行,执行多长时间. 进程 fork调用 通过fork()系统调用,就可以生成一个子进程 ...

  2. Python学习--18 进程和线程

    线程是最小的执行单元,而进程由至少一个线程组成.如何调度进程和线程,完全由操作系统决定,程序自己不能决定什么时候执行,执行多长时间. 进程 fork调用 通过fork()系统调用,就可以生成一个子进程 ...

  3. python学习之-- 进程 和 线程

    python 进程/线程详解 进程定义:以一个整体的形式暴露给操作系统管理,它里面包含对各种资源的调用,内存的管理,网络接口的调用等等,对各种资源管理的集合,就可以叫做一个进程. 线程定义:线程是操作 ...

  4. day34 python学习 守护进程,线程,互斥锁,信号量,生产者消费者模型,

    六 守护线程 无论是进程还是线程,都遵循:守护xxx会等待主xxx运行完毕后被销毁 需要强调的是:运行完毕并非终止运行 #1.对主进程来说,运行完毕指的是主进程代码运行完毕 #2.对主线程来说,运行完 ...

  5. python中的进程、线程(threading、multiprocessing、Queue、subprocess)

    Python中的进程与线程 学习知识,我们不但要知其然,还是知其所以然.你做到了你就比别人NB. 我们先了解一下什么是进程和线程. 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CP ...

  6. Python学习day38-并发编程(线程)

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  7. VC++学习之进程和线程的区别

    VC++学习之进程和线程的区别 一.进程        进程是表示资源分配的基本单位,又是调度运行的基本单位.例如,用户运行自己的程序,系统就创建一个进程,并为它分配资源,包括各种表格.内存空间.磁盘 ...

  8. JUC学习笔记——进程与线程

    JUC学习笔记--进程与线程 在本系列内容中我们会对JUC做一个系统的学习,本片将会介绍JUC的进程与线程部分 我们会分为以下几部分进行介绍: 进程与线程 并发与并行 同步与异步 线程详解 进程与线程 ...

  9. Python 中的进程、线程、协程、同步、异步、回调

    进程和线程究竟是什么东西?传统网络服务模型是如何工作的?协程和线程的关系和区别有哪些?IO过程在什么时间发生? 一.上下文切换技术 简述 在进一步之前,让我们先回顾一下各种上下文切换技术. 不过首先说 ...

随机推荐

  1. asp.net的forms身份验证 单用户身份验证

    asp.net的forms身份验证  单用户身份验证 首先要配置Web.config文件 <system.web> <authentication mode="Forms& ...

  2. Markdown分级语法手册

    目录 前言(可以不看) 基本语法(18) 1. 标题:# 2. 无序列表:- 3. 有序列表:1. 4. 斜体:* 5. 粗体:** 6. 加粗斜体:*** 7. 删除线:~~ 8. 分隔线:--- ...

  3. 1.openldap介绍

    1.openldap介绍 OpenLDAP是轻型目录访问协议(Lightweight Directory Access Protocol,LDAP)的自由和开源的实现,在其OpenLDAP许可证下发行 ...

  4. RIGHT-BICEP测试第二次程序

    根据Right-BICEP单元测试的方法我对我写的第二次程序进行了测试: 测试一:测试能否控制使用乘除 测试二:测试是否能加括号 测试三:是否可以控制题目输出数量 测试四:能否控制输出方式,选择文件输 ...

  5. 通俗理解Hilbert希尔伯特空间

    作者:qang pan 链接:https://www.zhihu.com/question/19967778/answer/28403912 来源:知乎 著作权归作者所有.商业转载请联系作者获得授权, ...

  6. python实现进制之间的转换

    十进制转36进制: #36位映射模板 loop = '0123456789abcdefghijklmnopqrstuvwxyz' # 测试用例输入 n = a = [] : a.append( loo ...

  7. java.lang.NoClassDefFoundError: Lcom/opensymphony/xwork2/util/logging/Logger tomcat6 启动错误

    用tomcat6启动时,出现下面的错误Java.lang.NoClassDefFoundError: Lcom/opensymphony/xwork2/util/logging/Logger; Cau ...

  8. layabox 3d 入手

    最近受到打击了,3d效果远比2d效果好. 问题 laya3d 有正交相机没有? Laya.Sprite3D.load(XX.lh);   克隆Laya.Sprite3D.instantiate Lay ...

  9. 【.Net】win10 uwp unix timestamp 时间戳 转 DateTime

    有时候需要把网络的 unix timestamp 转为 C# 的 DateTime ,在 UWP 可以如何转换? 转换函数可以使用下面的代码 private static DateTime UnixT ...

  10. js function的方法名是一个变量 能被重复定义 当变量名一致时候 会使用最后一个function