‘壹’ python 多线程
python支持多线程效果还不错,很多方面都用到了python 多线程的知识,我前段时间用python 多线程写了个处理生产者和消费者的问题,把代码贴出来给你看下:
#encoding=utf-8
import threading
import random
import time
from Queue import Queue
class Procer(threading.Thread):
def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print self.getName(),'adding',i,'to queue'
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'
# Consumer thread
class Consumer(threading.Thread):
def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print self.getName(),'got a value:',self.sharedata.get()
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'
# Main thread
def main():
queue = Queue()
procer = Procer('Procer', queue)
consumer = Consumer('Consumer', queue)
print 'Starting threads ...'
procer.start()
consumer.start()
procer.join()
consumer.join()
print 'All threads have terminated.'
if __name__ == '__main__':
main()
如果你想要了解更多的python 多线程知识可以点下面的参考资料的地址,希望对有帮助!
‘贰’ python循环怎么用多线程去运行
背景:Python脚本:读取文件中每行,放入列表中;循环读取列表中的每个元素,并做处理操作。
核心:多线程处理单个for循环函数调用
模块:threading
第一部分:
:多线程脚本 (该脚本只有两个线程,t1循环次数<t2)#!/usr/bin/env python#-*- coding: utf8 -*- import sysimport timeimport stringimport threadingimport datetimefileinfo = sys.argv[1] # 读取文件内容放入列表host_list = []port_list = [] # 定义函数:读取文件内容放入列表中def CreateList(): f = file(fileinfo,'r') for line in f.readlines(): host_list.append(line.split(' ')[0]) port_list.append(line.split(' ')[1]) return host_list return port_list f.close() # 单线程 循环函数,注释掉了#def CreateInfo(): # for i in range(0,len(host_list)): # 单线程:直接循环列表# time.sleep(1)# TimeMark = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')# print "The Server's HostName is %-15s and Port is %-4d !!! [%s]" % (host_list[i],int(port_list[i]),TimeMark)# # 定义多线程循环调用函数def MainRange(start,stop): #提供列表index起始位置参数 for i in range(start,stop): time.sleep(1) TimeMark = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print "The Server's HostName is %-15s and Port is %-4d !!! [%s]" % (host_list[i],int(port_list[i]),TimeMark) # 执行函数,生成列表CreateList()# 列表分割成:两部分 mid为列表的index中间位置mid = int(len(host_list)/2) # 多线程部分threads = []t1 = threading.Thread(target=MainRange,args=(0,mid))threads.append(t1)t2 = threading.Thread(target=MainRange,args=(mid,len(host_list)))threads.append(t2) for t in threads: t.setDaemon(True) t.start()t.join()print "ok"
以上是脚本内容!!!
----------------------------------------------------------------------
:读取文件的内容
文件内容:
[root@monitor2 logdb]# cat hostinfo.txt
192.168.10.11 1011
192.168.10.12 1012
192.168.10.13 1013
192.168.10.14 1014
192.168.10.15 1015
192.168.10.16 1016
192.168.10.17 1017
192.168.10.18 1018
192.168.10.19 1019
192.168.10.20 1020
192.168.10.21 1021
192.168.10.22 1022
192.168.10.23 1023
192.168.10.24 1024
192.168.10.25 1025
:输出结果:
单线程 : 执行脚本:输出结果:
[root@monitor2 logdb]# ./Threadfor.py hostinfo.txt
The Server's HostName is 192.168.10.10 and Port is 1010 !!! [2017-01-10 14:25:14]
The Server's HostName is 192.168.10.11 and Port is 1011 !!! [2017-01-10 14:25:15]
The Server's HostName is 192.168.10.12 and Port is 1012 !!! [2017-01-10 14:25:16]
.
.
.
The Server's HostName is 192.168.10.25 and Port is 1025 !!! [2017-01-10 14:25:29]
多线程:执行脚本:输出 结果
[root@monitor2 logdb]# ./Threadfor.py hostinfo.txt
The Server's HostName is 192.168.10.11 and Port is 1011 !!! [2017-01-10 14:51:51]
The Server's HostName is 192.168.10.18 and Port is 1018 !!! [2017-01-10 14:51:51]
The Server's HostName is 192.168.10.12 and Port is 1012 !!! [2017-01-10 14:51:52]
The Server's HostName is 192.168.10.19 and Port is 1019 !!! [2017-01-10 14:51:52]
The Server's HostName is 192.168.10.13 and Port is 1013 !!! [2017-01-10 14:51:53]
The Server's HostName is 192.168.10.20 and Port is 1020 !!! [2017-01-10 14:51:53]
The Server's HostName is 192.168.10.14 and Port is 1014 !!! [2017-01-10 14:51:54]
The Server's HostName is 192.168.10.21 and Port is 1021 !!! [2017-01-10 14:51:54]
The Server's HostName is 192.168.10.15 and Port is 1015 !!! [2017-01-10 14:51:55]
The Server's HostName is 192.168.10.22 and Port is 1022 !!! [2017-01-10 14:51:55]
The Server's HostName is 192.168.10.16 and Port is 1016 !!! [2017-01-10 14:51:56]
The Server's HostName is 192.168.10.23 and Port is 1023 !!! [2017-01-10 14:51:56]
The Server's HostName is 192.168.10.17 and Port is 1017 !!! [2017-01-10 14:51:57]
The Server's HostName is 192.168.10.24 and Port is 1024 !!! [2017-01-10 14:51:57]
The Server's HostName is 192.168.10.25 and Port is 1025 !!! [2017-01-10 14:51:58]
‘叁’ 日志文件太大,python怎么分割文件,多线程操作
python的多线程为伪多线程,多线程并不能提高文件IO的速度,在读取文件时使用直接读取 for line in open('文件名', 'r') 效率最高,因为此方式为直接读取,不像其它方式要把文件全部加载到内存再读取,所以效率最高。分割时文件时,提前计算好行数,把读取的每固定数量的行数存入新文件,直接读取完成,最后删除旧文件,即可实现文件分割。
示意代码:
line_count=0
index=0
fw=open('part'+str(index)+'.log','w')
forlineinopen('filename.log','r'):
fw.write(line)
line_count+=1
#假设每10000行写一个文件
ifline_count>10000:
fw.close()
index+=1
fw=open('part'+str(index)+'.log','w')
fw.close()
‘肆’ 如何使用Python进行多线程编程
1. 使用线程可以把占据长时间的程序中的任务放到后台去处理;
2. 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度;
3. 程序的运行速度可能加快;
4. 在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占用等等。
‘伍’ python 怎么用log函数
import sys
funcName = sys._getframe().f_back.f_code.co_name #获取调用函数名
lineNumber = sys._getframe().f_back.f_lineno #获取行号
print sys._getframe().f_code.co_name # 获取当前函数名
‘陆’ python如何使用多线程抓取多个log
由于python是一种解释性脚本语言,python的多线程在运行过程中始终存在全局线程锁。简单的来说就是在实际的运行过程中,python只能利用一个线程,因此python的多线程并不达到C语言多线程的性能。可以使用多进程来代替多线程,但需要注意的是多进程最好不要涉及到例如文件操作的频繁操作IO的功能。
‘柒’ python 多线程logger问题
因为logging是threadsafe的,但不是process-safe(应该没有这个词儿,只是为了便于理解)的。这段代码就是多个进程共同操作一个日志文件。这种情况下,logging的行为就很难说了。
我测试了一下,日志中大概几百行。而且,可以看到一些顺序错乱现象:
Fri, 08 Aug 2014 01:19:38 logging_in_multithread.py[line:40] theadWorking ERROR 2
FFri, 08 Aug 2014 01:19:36 logging_in_multithread.py[line:40] theadWorking ERROR 11(注意这里的FFri)
把代码这样改:
fornuminrange(processNum):
p=Process(target=processWorking,args=('2',))
processs.append(p)
p.start()
p.join()
还有其他方法,比如:为logging实现一个FileHandler,以使logging在multiple process的环境下也能正常工作。这是我从网上了解到的做法,自己还没实践过。
Python Manual中logging Cookbook中有这么一段话:
Logging to a single file from multiple processes
Although logging is thread-safe, and logging to a single file from multiple threads in a single process is supported, logging to a single file from multiple processes is not supported, because there is no standard way to serialize access to a single file across multiple processes in Python. If you need to log to a single file from multiple processes, one way of doing this is to have all the processes log to a SocketHandler, and have a separate process which implements a socket server which reads from the socket and logs to file. (If you prefer, you can dedicate one thread in one of the existing processes to perform this function.)
这段话中也提出了另外一种解决方案。
‘捌’ 如何理解python的多线程编程
线程是程序员必须掌握的知识,多线程对于代码的并发执行、提升代码效率和运行都至关重要。今天就分享一个黑马程序员Python多线程编程的教程,从0开始学习python多任务编程,想了解python高并发实现,从基础到实践,通过知识点 + 案例教学法帮助你想你想迅速掌握python多任务。
课程内容:
1.掌握多任务实现的并行和并发
2.掌握多进程实现多任务
3.掌握多线程实现多任务
4.掌握合理搭配多进程和线程
适用人群:
1、对python多任务编程感兴趣的在校生及应届毕业生。
2、对目前职业有进一步提升要求,希望从事python人工智能行业高薪工作的在职人员。
3、对python人工智能行业感兴趣的相关人员。
基础课程主讲内容包括:
1.python多任务编程
基础班课程大纲:
00-课程介绍
01-多任务介绍
02-进程介绍
03-使用多进程来完成多任务
04-多进程执行带有参数的任务
05-获取进程的编号
06-进程注意点
07-案例-多进程实现传智视频文件夹多任务拷贝器
08-线程介绍
09-使用多线程执行多任务
10-线程执行带有参数的任务
11-主线程和子线程的结束顺序
12-线程之间的执行顺序是无序
13-线程和进程的对比
14-案例-多线程实现传智视频文件夹多任务拷贝器
15-课程总结
‘玖’ python 怎么实现多线程的
线程也就是轻量级的进程,多线程允许一次执行多个线程,Python是多线程语言,它有一个多线程包,GIL也就是全局解释器锁,以确保一次执行单个线程,一个线程保存GIL并在将其传递给下一个线程之前执行一些操作,也就产生了并行执行的错觉。