在Python中通过threading模块定义和调用线程的方法


Posted in Python onJuly 12, 2016

定义线程

最简单的方法:使用target指定线程要执行的目标函数,再使用start()启动。

语法:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

group恒为None,保留未来使用。target为要执行的函数名。name为线程名,默认为Thread-N,通常使用默认即可。但服务器端程序线程功能不同时,建议命名。

#!/usr/bin/env python3
# coding=utf-8
import threading

def function(i):
  print ("function called by thread {0}".format(i))
threads = []

for i in range(5):
  t = threading.Thread(target=function , args=(i,))
  threads.append(t)
  t.start()
  t.join()

执行结果:

$ ./threading_define.py
function called by thread 0
function called by thread 1
function called by thread 2
function called by thread 3
function called by thread 4

确定当前线程

#!/usr/bin/env python3
# coding=utf-8

import threading
import time

def first_function():
  print (threading.currentThread().getName()+ str(' is Starting \n'))
  time.sleep(3)
  print (threading.currentThread().getName()+ str( ' is Exiting \n'))
  
def second_function():
  print (threading.currentThread().getName()+ str(' is Starting \n'))
  time.sleep(2)
  print (threading.currentThread().getName()+ str( ' is Exiting \n'))
  
def third_function():
  print (threading.currentThread().getName()+\
  str(' is Starting \n'))
  time.sleep(1)
  print (threading.currentThread().getName()+ str( ' is Exiting \n'))
  
if __name__ == "__main__":
  t1 = threading.Thread(name='first_function', target=first_function)
  t2 = threading.Thread(name='second_function', target=second_function)
  t3 = threading.Thread(name='third_function',target=third_function)
  t1.start()
  t2.start()
  t3.start()

执行结果:

$ ./threading_name.py
first_function is Starting 
second_function is Starting 
third_function is Starting 
third_function is Exiting 
second_function is Exiting 
first_function is Exiting

配合logging模块一起使用:

#!/usr/bin/env python3
# coding=utf-8

import logging
import threading
import time

logging.basicConfig(
  level=logging.DEBUG,
  format='[%(levelname)s] (%(threadName)-10s) %(message)s',
  )
  
def worker():
  logging.debug('Starting')
  time.sleep(2)
  logging.debug('Exiting')
  
def my_service():
  logging.debug('Starting')
  time.sleep(3)
  logging.debug('Exiting')
  
t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker) # use default name
w.start()
w2.start()
t.start()

执行结果:

$ ./threading_names_log.py[DEBUG] (worker  ) Starting
[DEBUG] (Thread-1 ) Starting
[DEBUG] (my_service) Starting
[DEBUG] (worker  ) Exiting
[DEBUG] (Thread-1 ) Exiting
[DEBUG] (my_service) Exiting

在子类中使用线程

前面我们的线程都是结构化编程的形式来创建。通过集成threading.Thread类也可以创建线程。Thread类首先完成一些基本上初始化,然后调用它的run()。run()方法会会调用传递给构造函数的目标函数。

#!/usr/bin/env python3
# coding=utf-8

import logging
import threading
import time

exitFlag = 0

class myThread (threading.Thread):
  def __init__(self, threadID, name, counter):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.name = name
    self.counter = counter
    
  def run(self):
    print ("Starting " + self.name)
    print_time(self.name, self.counter, 5)
    print ("Exiting " + self.name)
    
def print_time(threadName, delay, counter):
  while counter:
    if exitFlag:
      thread.exit()
    time.sleep(delay)
    print ("%s: %s" %(threadName, time.ctime(time.time())))
    counter -= 1
    
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print ("Exiting Main Thread")

执行结果:

$ ./threading_subclass.py
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Tue Sep 15 11:03:21 2015
Thread-2: Tue Sep 15 11:03:22 2015
Thread-1: Tue Sep 15 11:03:22 2015
Thread-1: Tue Sep 15 11:03:23 2015
Thread-2: Tue Sep 15 11:03:24 2015
Thread-1: Tue Sep 15 11:03:24 2015
Thread-1: Tue Sep 15 11:03:25 2015
Exiting Thread-1
Thread-2: Tue Sep 15 11:03:26 2015
Thread-2: Tue Sep 15 11:03:28 2015
Thread-2: Tue Sep 15 11:03:30 2015
Exiting Thread-2
Python 相关文章推荐
Python3基础之输入和输出实例分析
Aug 18 Python
Python聚类算法之基本K均值实例详解
Nov 20 Python
Python使用ntplib库同步校准当地时间的方法
Jul 02 Python
Python基于回溯法子集树模板解决取物搭配问题实例
Sep 02 Python
TF-IDF与余弦相似性的应用(一) 自动提取关键词
Dec 21 Python
python+pandas+时间、日期以及时间序列处理方法
Jul 10 Python
Python 通过requests实现腾讯新闻抓取爬虫的方法
Feb 22 Python
python实现多线程端口扫描
Aug 31 Python
Python3 把一个列表按指定数目分成多个列表的方式
Dec 25 Python
Python实现CAN报文转换工具教程
May 05 Python
PyCharm 2020.1版安装破解注册码永久激活(激活到2089年)
Sep 24 Python
基于python爬取链家二手房信息代码示例
Oct 21 Python
举例讲解Python编程中对线程锁的使用
Jul 12 #Python
使用Python编写一个最基础的代码解释器的要点解析
Jul 12 #Python
Python中使用bidict模块双向字典结构的奇技淫巧
Jul 12 #Python
Python使用SocketServer模块编写基本服务器程序的教程
Jul 12 #Python
使用Python的Flask框架表单插件Flask-WTF实现Web登录验证
Jul 12 #Python
Python的Flask框架标配模板引擎Jinja2的使用教程
Jul 12 #Python
深度定制Python的Flask框架开发环境的一些技巧总结
Jul 12 #Python
You might like
PHP中,文件上传
2006/12/06 PHP
jQuery+php实现ajax文件即时上传的详解
2013/06/17 PHP
php设计模式之单例模式使用示例
2014/01/20 PHP
php版本的cron定时任务执行器使用实例
2014/08/19 PHP
PHP中echo和print的区别
2014/08/28 PHP
php中opendir函数用法实例
2014/11/15 PHP
PHP实现操作redis的封装类完整实例
2015/11/14 PHP
PHP实现PDO操作mysql存储过程示例
2019/02/13 PHP
一个JavaScript用逗号分割字符串实例
2014/09/22 Javascript
js判断一个字符串是否包含一个子串的方法
2015/01/26 Javascript
jquery 设置style:display的方法
2015/01/29 Javascript
Javascript实现通过选择周数显示开始日和结束日的实现代码
2016/05/30 Javascript
微信小程序 scroll-view组件实现列表页实例代码
2016/12/14 Javascript
javascript 中关于array的常用方法详解
2017/05/05 Javascript
详解node单线程实现高并发原理与node异步I/O
2017/09/21 Javascript
解决vue中监听input只能输入数字及英文或者其他情况的问题
2018/08/30 Javascript
详解如何使用koa实现socket.io官网的例子
2018/11/04 Javascript
Vue路由模块化配置的完整步骤
2019/08/14 Javascript
使用JavaScrip模拟实现仿京东搜索框功能
2019/10/16 Javascript
解决vue里a标签值解析变量,跳转页面,前面加默认域名端口的问题
2020/07/22 Javascript
[55:48]VGJ.S vs TNC Supermajor 败者组 BO3 第二场 6.6
2018/06/07 DOTA
python基于pyDes库实现des加密的方法
2017/04/29 Python
在matplotlib的图中设置中文标签的方法
2018/12/13 Python
python numpy 按行归一化的实例
2019/01/21 Python
python设计tcp数据包协议类的例子
2019/07/23 Python
Python3.8对可迭代解包的改进及用法详解
2019/10/15 Python
使用python模拟高斯分布例子
2019/12/09 Python
使用Pycharm分段执行代码
2020/04/15 Python
DjangoWeb使用Datatable进行后端分页的实现
2020/05/18 Python
Python非单向递归函数如何返回全部结果
2020/12/18 Python
html5+css3进度条倒计时动画特效代码【推荐】
2016/03/08 HTML / CSS
Why do we need Unit test
2013/01/03 面试题
药品质量检测应届生求职信
2013/11/14 职场文书
求职简历中自我评价
2014/01/28 职场文书
金融学专业大学生职业生涯规划
2014/03/07 职场文书
pytorch model.cuda()花费时间很长的解决
2021/06/01 Python