记录瞬间

=====================其一=====================

# 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两段多线程的例子的更多相关文章

  1. 如何把Excel表暴力拆分了,python两段代码帮你搞定

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:老方玩编程 PS:如有需要Python学习资料的小伙伴可以加点击下方 ...

  2. python多线程简单例子

    python多线程简单例子 作者:vpoet mail:vpoet_sir@163.com import thread def childthread(threadid): print "I ...

  3. python高级之多线程

    python高级之多线程 本节内容 线程与进程定义及区别 python全局解释器锁 线程的定义及使用 互斥锁 线程死锁和递归锁 条件变量同步(Condition) 同步条件(Event) 信号量 队列 ...

  4. python之路-----多线程与多进程

    一.进程和线程的概念 1.进程(最小的资源单位): 进程:就是一个程序在一个数据集上的一次动态执行过程.进程一般由程序.数据集.进程控制块三部分组成. 程序:我们编写的程序用来描述进程要完成哪些功能以 ...

  5. 2016/1/2 Python中的多线程(1):线程初探

    ---恢复内容开始--- 新年第一篇,继续Python. 先来简单介绍线程和进程. 计算机刚开始发展的时候,程序都是从头到尾独占式地使用所有的内存和硬件资源,每个计算机只能同时跑一个程序.后来引进了一 ...

  6. python并发编程&多线程(二)

    前导理论知识见:python并发编程&多线程(一) 一 threading模块介绍 multiprocess模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性 官网链 ...

  7. Python多进程与多线程编程及GIL详解

    介绍如何使用python的multiprocess和threading模块进行多线程和多进程编程. Python的多进程编程与multiprocess模块 python的多进程编程主要依靠multip ...

  8. python基础-12 多线程queue 线程交互event 线程锁 自定义线程池 进程 进程锁 进程池 进程交互数据资源共享

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

  9. python中的多线程【转】

    转载自: http://c4fun.cn/blog/2014/05/06/python-threading/ python中关于多线程的操作可以使用thread和threading模块来实现,其中th ...

随机推荐

  1. There is no getter for property named 'XXX' in 'class java.lang.String'解决方法

    <select id="ProjectHomePage" parameterType="string" resultType="java.uti ...

  2. Mac安装软件包管理工具Homebrew

    PS:最近开始学习groovy,打算去官网下载SDK Bundle,可是官网半天加载不出来,而且莫名其妙就是下载不下来,Folx一直提示 "无效的HTTP相应:禁止",可能是插件和 ...

  3. Java Base64 加解密

    public class base64EncryAndDecry { public static final String CODES = "ABCDEFGHIJKLMNOPQRSTUVWX ...

  4. laravel之模型操作

    首先在App下创建模型,一个模型对应着一个表: 2.创建好模型之后,使用控制器来操作模型 先使用模型 创建方法来使用模型(记得要添加路由)

  5. ElasticSeaarch 遇到的问题 (-)

    1 elasticSearch 不能通过ip访问 智只能通过localhost访问,或者在外网部署的时候不能访问: elasticsearch.yml文件 中将下面的配置去掉注释符,  network ...

  6. Web应用程序架构的比较

    架构 技术优势 技术挑战 团队优势 团队挑战 单体 低延时 开发简单 没有重复的模型/验证 伸缩 由于代码库过大引起的复杂度 特性内沟通的开销低 失败的恐惧 特性间沟通的开销大 前端+后端 能够单独扩 ...

  7. Web Service学习(一)

    1.WebMethod特性包含哪些属性,都有什么用? 1.BufferResponse属性 该属性表明是否启用对Web Service方法响应的缓冲.当设置为true时,Web Service方法将响 ...

  8. 经过N条边的最短路

    http://acm.pku.edu.cn/JudgeOnline/problem?id=3613 求经过N条边的最短路 (2 ≤ N ≤ 1,000,000) 倍增floyd,主体是矩阵乘法.考虑一 ...

  9. Collections类

    1:一个类对象之间的比较两种方法 1)实现Comparator<String>类并且从写Comparator类中的compare方法, public class A implements ...

  10. java实现求最大子数组和的逐步显示

    package 最大的子数组和; import java.util.Scanner; public class shuzu { public static int maxArr(int a[]) { ...