记录瞬间

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

# 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. webpack 打包测试和生产多个版本

    cross-env修改生产环境变量 npm i --save-dev cross-env 在package.json里这么配置 npm run build就是打包到生产环境 npm run build ...

  2. Lesnoe Ozero 2017. BSUIR Open 2017

    A. Tree Orientation 树形DP,$f[i][j][k]$表示$i$的子树中有$j$个汇点,$i$往父亲的树边方向为$k$的方案数. 转移则需要另一个DP:$g[i][j][k]$表示 ...

  3. Hibernate 映射一对一关联关系

    基于外键的方式: 附上代码: public class Manager { private Integer mgrId; private String mgrName; private Departm ...

  4. SpringMVC用到的jar包

    SpringMVC用到的jar包 自己搭建一个SpringMVC框架时需要用到相应的jar包,参考下载网址: http://repo.spring.io/release/org/springframe ...

  5. NOIP-金币

    题目描述 国王将金币作为工资,发放给忠诚的骑士.第一天,骑士收到一枚金币:之后两天(第二天和第三天),每天收到两枚金币:之后三天(第四.五.六天),每天收到三枚金币:之后四天(第七.八.九.十天),每 ...

  6. 简单的3d变换

    <!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title> ...

  7. Nginx配置:nginx如何配置跳转fpm

    location ~ \.php(.*)$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_split_path_inf ...

  8. svn的简单学习与日常使用

  9. c++ 库函数cmath

    cmath中常用库函数: int abs(int i);//返回整型参数i的绝对值double fabs(double x);//返回双精度参数x的绝对值long labs(long n);//返回长 ...

  10. Maven多模块项目编译失败:程序包xxx不存在

    项目结构如下: parent(父类工程) | - - - - - common(通用工具类子工程) | - - - - - projectA(springboot子工程,依赖common工程) pom ...