python网络编程之进程池

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37886429/article/details/85064144

一、Socket简介

socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求。
socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,对于文件用【打开】【读写】【关闭】模式来操作。socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)

socket和file的区别:
file模块是针对某个指定文件进行【打开】【读写】【关闭】
socket模块是针对 服务器端 和 客户端Socket 进行【打开】【读写】【关闭】

socket server

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import socket

ip_port = ('127.0.0.1',9999)

sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)

while True:
    print 'server waiting...'
    conn,addr = sk.accept()

    client_data = conn.recv(1024)
    print client_data
    conn.sendall('不要回答,不要回答,不要回答')

    conn.close()

socket client

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
ip_port = ('127.0.0.1',9999)

sk = socket.socket()
sk.connect(ip_port)

sk.sendall('请求占领地球')
server_reply = sk.recv(1024)
print server_reply
sk.close()

web服务器应用

#!/usr/bin/env python
#coding:utf-8
import socket
 
def handle_request(client):
    buf = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n")
    client.send("Hello, World")
 
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost',8080))
    sock.listen(5)
 
    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()
 
if __name__ == '__main__':
  main()

二、多进程

1、Pool使用简介
有些情况下,所要完成的工作可以分解并独立地分布到多个工作进程,对于这种简单的情况,可以用Pool类来管理固定数目的工作进程。
示例一:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import time
from multiprocessing import Pool

def run(fn):
    time.sleep(1)
    print(fn*fn)

if __name__ == '__main__':
    testFL = [1,2,3,4,5,6]
    print('顺序执行或者叫做串行执行,也叫单进程')
    s = time.time()
    for i in testFL:
        run(i)
    t1 = time.time()
    print('顺序执行时间:',int(t1-s))

    #===============
    print('创建多个进程,并行执行')
    pool = Pool(6)  #创建拥有6个进程数量的进程池
    pool.map(run,testFL)  #testFL:要处理的数据列表,run:处理testFL列表中的数据函数
    pool.close()  #关闭进程池,不再接受新的进程
    pool.join()   #主进程阻塞等待子进程的退出
    t2 = time.time()
    print('并行执行时间:',int(t2-t1))

示例二:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import time
from datetime import datetime
from multiprocessing.dummy import Pool as ThreadPool

def add(x, y):
    print(datetime.now(), "enter add func...")
    time.sleep(2)
    print(datetime.now(), "leave add func...")
    return x+y

def add_wrap(args):
    return add(*args)

if __name__ == "__main__":
    pool = ThreadPool(4) # 池的大小为4
    print(pool.map(add_wrap, [(1,2),(3,4),(5,6)]))
    #close the pool and wait for the worker to exit
    pool.close()
    pool.join()

备注:池完成其所分配的任务时,即使没有更多的工作要做,也会重新启动工作进程。

2、进程执行结果

#!/usr/bin/env python
#-*- coding:utf-8 -*-
from multiprocessing import Pool
import time

def func(msg):
    for i in range(3):
        print(msg)
        time.sleep(1)
    return "done " + msg

if __name__ == "__main__":
    pool = Pool(processes=4)
    result = []
    for i in range(10):
        msg = "hello %d" %(i)
        result.append(pool.apply_async(func, (msg,)))
    pool.close()
    pool.join()
    for res in result:
        print(res.get())
    print("Sub-process(es) done.")

猜你喜欢

转载自blog.csdn.net/m0_37886429/article/details/85064144
今日推荐