python实现多线程的两种方式

作者:赵浮云的blog 时间:2022-09-30 00:54:15 

目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。
2.7版本之前python对线程的支持还不够完善,不能利用多核CPU,但是2.7版本的python中已经考虑改进这点,出现了multithreading  模块。threading模块里面主要是对一些线程的操作对象化,创建Thread的class。一般来说,使用线程有两种模式:

A 创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;
B 继承Thread类,创建一个新的class,将要执行的代码 写到run函数里面。

本文介绍两种实现方法。
第一种 创建函数并且传入Thread 对象中
t.py 脚本内容


import threading,time
from time import sleep, ctime
def now() :
 return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
def test(nloop, nsec):
 print 'start loop', nloop, 'at:', now()
sleep(nsec)
 print 'loop', nloop, 'done at:', now()
def main():
 print 'starting at:',now()
 threadpool=[]
for i in xrange(10):
   th = threading.Thread(target= test,args= (i,2))
   threadpool.append(th)
for th in threadpool:
   th.start()
for th in threadpool :
   threading.Thread.join( th )
 print 'all Done at:', now()
if __name__ == '__main__':
   main()

 thclass.py 脚本内容:


import threading ,time
from time import sleep, ctime
def now() :
 return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
class myThread (threading.Thread) :
"""docstring for myThread"""
  def __init__(self, nloop, nsec) :
    super(myThread, self).__init__()
    self.nloop = nloop
    self.nsec = nsec
  def run(self):
    print 'start loop', self.nloop, 'at:', ctime()
sleep(self.nsec)
    print 'loop', self.nloop, 'done at:', ctime()
def main():
  thpool=[]
  print 'starting at:',now()
for i in xrange(10):
    thpool.append(myThread(i,2))
for th in thpool:
    th.start()
for th in thpool:
    th.join()
  print 'all Done at:', now()
if __name__ == '__main__':
   main()
标签:python,多线程
0
投稿

猜你喜欢

  • Django drf分页器的使用详解

    2022-04-09 08:23:35
  • Python实现数据集划分(训练集和测试集)

    2022-11-29 23:54:11
  • python [:3] 实现提取数组中的数

    2022-06-29 07:46:19
  • 深入理解PyTorch中的nn.Embedding的使用

    2023-01-25 11:54:02
  • 给你选择Python语言实现机器学习算法的三大理由

    2023-08-20 23:10:26
  • 详解Python中的进程和线程

    2021-10-06 21:49:03
  • Oracle导出excel数据

    2023-07-18 17:44:14
  • Django配置kafka消息队列的实现

    2023-07-19 00:49:27
  • Extjs显示从数据库取出时间转换JSON后的出现问题

    2024-01-18 12:52:13
  • innerHTML,outerHTML,innerText,outerText用法

    2008-02-15 12:22:00
  • python getopt 参数处理小示例

    2021-03-02 13:05:02
  • Python利用matplotlib实现制作动态条形图

    2021-06-11 05:29:15
  • js如何读取csv内容拼接成json

    2023-08-13 02:20:14
  • 使用面向对象的技术创建高级JavaScript Web 应用程序

    2008-11-03 13:00:00
  • 识别操作系统是不是vista的js代码

    2013-10-20 19:08:25
  • php实现的一段简单概率相关代码

    2023-11-23 02:20:28
  • 解决PHP 7编译安装错误:cannot stat ‘phar.phar’: No such file or directory

    2023-09-05 06:07:44
  • python使用正则表达式匹配字符串开头并打印示例

    2021-07-02 00:52:13
  • 浅谈python3.6的tkinter运行问题

    2021-08-04 01:29:16
  • 玩转python爬虫之爬取糗事百科段子

    2022-09-23 12:20:52
  • asp之家 网络编程 m.aspxhome.com