python两段多线程的例子
记录瞬间
=====================其一=====================
# coding:UTF-8
import os
import threading
from time import ctime def loop(loops, list): # list存放着每个线程需要处理的文本文件名
print('线程 %d 处理的文件列表 %s \n' % (loops + 1, list))
list_len = len(list)
for i in range(list_len):
f = open(list[i], mode="r", encoding="UTF-8")
rows = len(f.readlines()) # 此处,我直接将整个文件读入,所以会比较卡,可以在此设置每次读入的大小
f.close()
print('文件 %s __ %d 行\n' % (list[i], rows)) def main():
print('all start at:', ctime())
cwd = os.getcwd()
dir_list = os.listdir(cwd)
file_list = [] # 该列表用来存放当前目录下的所有txt文件
print('当前文件夹 {} 下的所有txt文件:'.format(dir_list))
for l in dir_list:
if l.rfind('log') >= 0 and os.path.isfile(l):
print(' ', l)
file_list.append(l)
threads = []
threads_num = 4 # 线程数 在此处修改下线程数就可以比较多线程与单线程处理文件的速度差异
print('共有线程数:%d个' % threads_num)
per_thread = len(file_list) / threads_num # 每个线程处理的文本数量
print(per_thread)
for i in range(threads_num):
if threads_num - i == 1: # 最后一个线程,分担余下的所有工作量
t = threading.Thread(target=loop, args=(i, file_list[i * int(per_thread):]))
else:
t = threading.Thread(target=loop, args=(i, file_list[i * int(per_thread):
i * int(per_thread) + int(per_thread)]))
threads.append(t)
for i in range(threads_num):
threads[i].start()
for i in range(threads_num): # 等待所有的线程结束
threads[i].join()
print('all end at:', ctime()) if __name__ == '__main__':
main()
上述代码,主要解决了多线程在进行读写时使用的一些技巧,可以将这段代码引用于写一套文件上,然后将多线程写的文件做以合并。这样可以很好的解决执行速度的问题。
=====================其二=====================
混合使用多进程和多线程的例子。
#!/usr/bin/python
import re
import commands
import time
import multiprocessing
import threading def download_image(url):
print '*****the %s rpm begin to download *******' % url
commands.getoutput('wget %s' % url) def get_rpm_url_list(url):
commands.getoutput('wget %s' % url)
rpm_info_str = open('index.html').read() regu_mate = '(?<=<a href=")(.*?)(?=">)'
rpm_list = re.findall(regu_mate, rpm_info_str) rpm_url_list = [url + rpm_name for rpm_name in rpm_list]
print 'the count of rpm list is: ', len(rpm_url_list)
return rpm_url_list
基础方法定义 =↑=
def multi_thread(rpm_url_list):
threads = []
# url = 'https://mirrors.ustc.edu.cn/centos/7/os/x86_64/Packages/'
# rpm_url_list = get_rpm_url_list(url)
for index in range(len(rpm_url_list)):
print 'rpm_url is:', rpm_url_list[index]
one_thread = threading.Thread(target=download_image, args=(rpm_url_list[index],))
threads.append(one_thread) thread_num = 5 # set threading pool, you have put 4 threads in it
while 1:
count = min(thread_num, len(threads))
print '**********count*********', count ###25,25,...6707%25 res = []
for index in range(count):
x = threads.pop()
res.append(x)
for thread_index in res:
thread_index.start() for j in res:
j.join() if not threads:
break
多线程的定义 =↑=
def multi_process(rpm_url_list):
# process num at the same time is 4
process = []
rpm_url_group_0 = []
rpm_url_group_1 = []
rpm_url_group_2 = []
rpm_url_group_3 = [] for index in range(len(rpm_url_list)):
if index % 4 == 0:
rpm_url_group_0.append(rpm_url_list[index])
elif index % 4 == 1:
rpm_url_group_1.append(rpm_url_list[index])
elif index % 4 == 2:
rpm_url_group_2.append(rpm_url_list[index])
elif index % 4 == 3:
rpm_url_group_3.append(rpm_url_list[index])
rpm_url_groups = [rpm_url_group_0, rpm_url_group_1, rpm_url_group_2, rpm_url_group_3]
for each_rpm_group in rpm_url_groups:
each_process = multiprocessing.Process(target = multi_thread, args = (each_rpm_group,))
process.append(each_process) for one_process in process:
one_process.start() for one_process in process:
one_process.join() # for each_url in rpm_url_list:
# print '*****the %s rpm begin to download *******' %each_url
#
# commands.getoutput('wget %s' %each_url)
多进程调用多线程的定义 =↑=
def main():
url = 'https://mirrors.ustc.edu.cn/centos/7/os/x86_64/Packages/'
url_paas = 'http://mirrors.ustc.edu.cn/centos/7.3.1611/paas/x86_64/openshift-origin/'
url_paas2 ='http://mirrors.ustc.edu.cn/fedora/development/26/Server/x86_64/os/Packages/u/' start_time = time.time()
rpm_list = get_rpm_url_list(url_paas)
print multi_process(rpm_list)
# print multi_thread(rpm_list)
#print multi_process()
# print multi_thread(rpm_list)
# for index in range(len(rpm_list)):
# print 'rpm_url is:', rpm_list[index]
end_time = time.time()
print 'the download time is:', end_time - start_time print main()
主方法 =↑=
代码来源:https://blog.csdn.net/nfzhlk/article/details/76946281
其中获取cpu核数的方法可以使用
from multiprocessing import cpu_count
print(cpu_count())
一般地,想要多线程快速做事情,我们不加锁,加了锁后,容易导致执行的效率跟单线程保持一致了。
这样做不划算,当然要看具体的需求是否需要使用多线程加锁的方式。
python两段多线程的例子的更多相关文章
- 如何把Excel表暴力拆分了,python两段代码帮你搞定
前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:老方玩编程 PS:如有需要Python学习资料的小伙伴可以加点击下方 ...
- python多线程简单例子
python多线程简单例子 作者:vpoet mail:vpoet_sir@163.com import thread def childthread(threadid): print "I ...
- python高级之多线程
python高级之多线程 本节内容 线程与进程定义及区别 python全局解释器锁 线程的定义及使用 互斥锁 线程死锁和递归锁 条件变量同步(Condition) 同步条件(Event) 信号量 队列 ...
- python之路-----多线程与多进程
一.进程和线程的概念 1.进程(最小的资源单位): 进程:就是一个程序在一个数据集上的一次动态执行过程.进程一般由程序.数据集.进程控制块三部分组成. 程序:我们编写的程序用来描述进程要完成哪些功能以 ...
- 2016/1/2 Python中的多线程(1):线程初探
---恢复内容开始--- 新年第一篇,继续Python. 先来简单介绍线程和进程. 计算机刚开始发展的时候,程序都是从头到尾独占式地使用所有的内存和硬件资源,每个计算机只能同时跑一个程序.后来引进了一 ...
- python并发编程&多线程(二)
前导理论知识见:python并发编程&多线程(一) 一 threading模块介绍 multiprocess模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性 官网链 ...
- Python多进程与多线程编程及GIL详解
介绍如何使用python的multiprocess和threading模块进行多线程和多进程编程. Python的多进程编程与multiprocess模块 python的多进程编程主要依靠multip ...
- python基础-12 多线程queue 线程交互event 线程锁 自定义线程池 进程 进程锁 进程池 进程交互数据资源共享
Python中的进程与线程 学习知识,我们不但要知其然,还是知其所以然.你做到了你就比别人NB. 我们先了解一下什么是进程和线程. 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CP ...
- python中的多线程【转】
转载自: http://c4fun.cn/blog/2014/05/06/python-threading/ python中关于多线程的操作可以使用thread和threading模块来实现,其中th ...
随机推荐
- Facebook授权登录
1.注册开发者账号 登陆facebook开发者平台 (https://developers.facebook.com/), 注册facebook开发者账号. 2.Facebook登录Key Hash配 ...
- python基础篇_006_面向对象
面向对象 1.初识类: # 定义一个函数,我们使用关键字 def """ def 函数名(参数): '''函数说明''' 函数体 return 返回值 "&qu ...
- 阿里云负载均衡SSL证书配置(更新)
阿里云负载均衡及应用防火墙SSL证书配置 转载请注明地址:http://www.cnblogs.com/funnyzpc/p/8908461.html 好久了呢,距上篇博客的这段时间中:考试.搬家.工 ...
- 03-Python入门学习-Python基础
一.与用户交互 1.什么是与用户交互 程序等待用户输入一些数据,然后程序执行完毕后为用户反馈信息 2.为何程序要与用户交互 为了让计算机能够像人一样与用户的交互 3.如何用 在python3中:inp ...
- VS2008,System.Runtime.InteropServices.COMException (0x800401F3): Invalid class string (Exception from HRESULT: 0x800401F3 (CO_E_CLASSSTRING))
在VS2008环境中编译调试运行不报错,但在发布的exe文件运行就报错 System.Runtime.InteropServices.COMException (0x800401F3): Invali ...
- 转 MYSQL SELECT ... FOR UPDATE and SELECT ... LOCK IN SHARE MODE Locking Reads
原文: http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html In some circumstances, a consis ...
- 运用了css,js
代码如下: <!DOCTYPE html><html xmlns="http://www.w3.org/1999/html"><head> &l ...
- SPARK-18560
##### Receiver data can not be dataSerialized properly. ``` // :: ERROR executor.Executor: Exception ...
- Ringo替换Paul
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- Python读取xlsx翻译文案
首先安装Python,然后安装模块 //查找模块(非必须) pip search xlrd //安装模块 pip install xlrd 由于输出要是utf-8所以需要设置默认环境为utf-8 # ...