python基础-线程创建、线程池、进\线程异步回调(add_done_callback)、进\线程数据共享、ftp线程池

本文主要是介绍python基础-线程创建、线程池、进\线程异步回调(add_done_callback)、进\线程数据共享、ftp线程池,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

      • 线程创建
      • 线程进程pid
      • 线程进程数据共享
      • 线程ftp
      • 线程池
      • 线程池ftp
      • 线程的一些其他方法
      • 异步-回调函数
        • ProcessPoolExecutor方式
        • ThreadPoolExecutor方式

线程创建

进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合),而线程才是cpu上的执行单位。
每个进程有一个地址空间,而且默认就有一个控制线程
线程就是一条流水线工作的过程,一条流水线必须属于一个车间,一个车间的工作过程是一个进程

多线程(即多个控制线程)的概念是,在一个进程中存在多个控制线程,多个控制线程共享该进程的地址空间,相当于一个车间内有多条流水线,都共用一个车间的资源

我们之前了解过进程的2种创建方式
下面的代码是2种创建线程的方式

from threading import Thread
from multiprocessing import Process
import time,osdef task():print('%s is running' %os.getpid())time.sleep(2)print('%s is done' %os.getpid())class Mythread(Thread):def __init__(self,name):super().__init__()self.name=namedef run(self):print('%s is running' % os.getpid())time.sleep(5)print('%s is done' % os.getpid())if __name__ == '__main__':t=Thread(target=task)# t=Mythread('xxxxx')t.start()print('主')

输出如下:

E:\python\python_sdk\python.exe "E:/python/py_pro/1 开启线程的两种方式.py"
10336 is running
主
10336 is doneProcess finished with exit code 0

线程进程pid

part1:在主进程下开启多个线程,每个线程都跟主进程的pid一样

from threading import Thread
from multiprocessing import Process
import time,osdef task():print('partent:%s self:%s' %(os.getppid(),os.getpid()))time.sleep(5)if __name__ == '__main__':t=Thread(target=task,)# t=Process(target=task,)t.start()print('主',os.getppid(),os.getpid())

输出如下:

partent:9052 self101209052 10120

开多个进程,每个进程都有不同的pid

from threading import Thread
from multiprocessing import Process
import time,osdef task():print('partent:%s self:%s' %(os.getppid(),os.getpid()))time.sleep(5)if __name__ == '__main__':t=Process(target=task,)t.start()print('主',os.getppid(),os.getpid())

输出如下:

9052 2668
partent:2668 self8744

线程进程数据共享

进程之间数据不共享,但是进程之间可以通过ipc进行数据通讯

from threading import Thread
from multiprocessing import Process
import time,osn=100
def task():global nn=0if __name__ == '__main__':t=Process(target=task,)t.start()t.join()print('主',n)

输出如下:

主 100

线程之间内存空间共享

from threading import Thread
import time,osn=100
def task():global nn=0if __name__ == '__main__':t=Thread(target=task,)t.start()t.join()print('主',n)

输出如下:

主 0

线程ftp

服务端:

import multiprocessing
import threadingimport socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('127.0.0.1',8081))
s.listen(5)def action(conn):while True:data=conn.recv(1024)print(data)conn.send(data.upper())if __name__ == '__main__':while True:conn,addr=s.accept()p=threading.Thread(target=action,args=(conn,))p.start()

客户端:

from socket import *client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8081))while True:msg=input('>>: ').strip()if not msg:continueclient.send(msg.encode('utf-8'))msg=client.recv(1024)print(msg.decode('utf-8'))

线程池

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from threading import current_thread
import time,random
def task(n):print('%s is running' %current_thread().getName())time.sleep(random.randint(1,3))return n**2if __name__ == '__main__':t=ThreadPoolExecutor(3) #默认是cpu的核数*5objs=[]for i in range(5):obj=t.submit(task,i)objs.append(obj)t.shutdown(wait=True)for obj in objs:print(obj.result())print('主',current_thread().getName())

输出如下:

E:\python\python_sdk\python.exe "E:/python/py_pro/4 线程池.py"
ThreadPoolExecutor-0_0 is running
ThreadPoolExecutor-0_1 is running
ThreadPoolExecutor-0_2 is runningThreadPoolExecutor-0_0 is runningThreadPoolExecutor-0_1 is running0
1
4
9
16
主 MainThread

线程池ftp

服务端:

from socket import *
from concurrent.futures import ThreadPoolExecutor
import osserver=socket(AF_INET,SOCK_STREAM)
server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
server.bind(('127.0.0.1',8080))
server.listen(5)def talk(conn,client_addr):print('进程pid: %s' %os.getpid())while True:try:msg=conn.recv(1024)if not msg:breakconn.send(msg.upper())except Exception:breakif __name__ == '__main__':p=ThreadPoolExecutor(5)while True:conn,client_addr=server.accept()p.submit(talk,conn,client_addr)

客户端:

from socket import *client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8081))while True:msg=input('>>: ').strip()if not msg:continueclient.send(msg.encode('utf-8'))msg=client.recv(1024)print(msg.decode('utf-8'))

线程的一些其他方法

from threading import Thread,current_thread,enumerate,active_count
import time,osdef task():print('%s is running' %current_thread().getName())time.sleep(5)print('%s is done' %current_thread().getName())if __name__ == '__main__':t=Thread(target=task,name='xxxx')t.start()print(t.name)#查看当前活着的线程print(enumerate()[0].getName())print(active_count())print('主',current_thread().getName())print()

输出如下:

E:\python\python_sdk\python.exe "E:/python/py_pro/3 线程对象的其他属性或方法.py"
xxxx is running
xxxx
MainThread
2
主 MainThreadxxxx is done

异步-回调函数

ProcessPoolExecutor方式

我们之前总结的异步返回结果没有用到调用函数,接下来的是利用了回调函数

#pip install requests
import requests
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from threading import current_thread
import time,os
def get(url):print('%s GET %s' %(os.getpid(),url))response=requests.get(url)time.sleep(3)if response.status_code == 200:return {'url':url,'text':response.text}def parse(obj):res=obj.result()print('[%s] <%s> (%s)' % (os.getpid(), res['url'],len(res['text'])))if __name__ == '__main__':urls = ['https://www.python.org','https://www.baidu.com','https://www.jd.com','https://www.tmall.com',]t=ProcessPoolExecutor(2)for url in urls:t.submit(get,url).add_done_callback(parse)t.shutdown(wait=True)print('主',os.getpid())

代码思路是:
t=ProcessPoolExecutor(2)开一个进程池,然后去并发下载网络数据,下载完毕后,
在主进程中add_done_callback去解析
这里由于主进程、子进程不是同一个进程空间,所以在解析数据时候,在主进程
输出如下:

E:\python\python_sdk\python.exe "E:/python/py_pro/5 补充异步的概念.py"
5628 GET https://www.python.org
4816 GET https://www.baidu.com4816 GET https://www.jd.com
[3204] <https://www.baidu.com> (2443)[3204] <https://www.python.org> (48856)
5628 GET https://www.tmall.com[3204] <https://www.jd.com> (124541)[3204] <https://www.tmall.com> (212080)
主 3204Process finished with exit code 0
ThreadPoolExecutor方式
import requests
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from threading import current_thread
import time
import os
def get(url):print('%s GET %s,%s' %(current_thread().getName(),os.getpid(),url))response=requests.get(url)time.sleep(3)if response.status_code == 200:return {'url':url,'text':response.text}def parse(obj):res=obj.result()print('[%s] <%s> (%s)' % (current_thread().getName(), res['url'],len(res['text'])))if __name__ == '__main__':urls = ['https://www.python.org','https://www.baidu.com','https://www.jd.com','https://www.tmall.com',]t=ThreadPoolExecutor(2)for url in urls:t.submit(get,url).add_done_callback(parse)t.shutdown(wait=True)print('主',current_thread().getName(),os.getpid())

代码思路是:
t=ThreadPoolExecutor(2)开一个线程池,然后去并发下载网络数据,下载完毕后,
在主线程程中add_done_callback去解析
这里由于主线程、子线程是同一个进程空间,所以在解析数据时候,可能主线程、子线程都会解析
输出如下:

E:\python\python_sdk\python.exe "E:/python/py_pro/5 补充异步的概念.py"
ThreadPoolExecutor-0_0 GET 12956,https://www.python.org
ThreadPoolExecutor-0_1 GET 12956,https://www.baidu.com[ThreadPoolExecutor-0_1] <https://www.baidu.com> (2443)
ThreadPoolExecutor-0_1 GET 12956,https://www.jd.com[ThreadPoolExecutor-0_0] <https://www.python.org> (48856)
ThreadPoolExecutor-0_0 GET 12956,https://www.tmall.com[ThreadPoolExecutor-0_1] <https://www.jd.com> (124541)[ThreadPoolExecutor-0_0] <https://www.tmall.com> (212079)
主 MainThread 12956Process finished with exit code 0

这篇关于python基础-线程创建、线程池、进\线程异步回调(add_done_callback)、进\线程数据共享、ftp线程池的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125193

相关文章

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Javaee多线程之进程和线程之间的区别和联系(最新整理)

《Javaee多线程之进程和线程之间的区别和联系(最新整理)》进程是资源分配单位,线程是调度执行单位,共享资源更高效,创建线程五种方式:继承Thread、Runnable接口、匿名类、lambda,r... 目录进程和线程进程线程进程和线程的区别创建线程的五种写法继承Thread,重写run实现Runnab

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核