在Python中通过threading模块定义和调用线程的方法
作者:磁针石 发布时间:2022-03-08 23:23:49
标签:Python,threading
定义线程
最简单的方法:使用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
0
投稿
猜你喜欢
- 本人就职于一个本地门户网站,每天网站上的天气都得更新。久而久之感到相当麻烦,于是写了一个定时的新闻小偷,帖出来大家参考一下系统
- 文章主要讲术了一些SQL Server新的Bug,帮您认识这些被忽略的SQL Server注入技巧。1.关于Openrowset和Opend
- 用ASP判断一个字符串中只包含字母和数字要怎么做啊? for s=1 to len(trim(use
- function chinese2unicode(Str) &nbs
- 接着第一篇继续学习。一、数据分类正确数据:id、性别、活动时间三者都有放在这个文件里file1 = 'ruisi\\correct%
- 引言提到 numpy 的数组操作,我们就不得不说到 np.concatenate() 函数,concatenate 一词在英文中是级联的意思
- 引言:闲来想到冒泡排序中的列表数据的排序,就想试试用随机数生成一个列表来排序试试,于是做了一下实验,本人实在是属于入门阶段,研究了一下终究还
- 这篇文章主要介绍了Python实现序列化及csv文件读取,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 正在看的ORACLE教程是:Oracle 数据表分区的策略。本文描述通过统计分析出医院信息系统需分区的表,对需分区的表选择分区键,即找出包括
- 本文实例讲述了PHP学习记录之面向对象(Object-oriented programming,OOP)基础。分享给大家供大家参考,具体如下
- 一些大型站点都有着非常一流的视觉外观,它们很可能在设计时使用了网格系统。网格可以是页面布局显得紧凑而且稳定,为设计师在设计站点时提供一个逻辑
- Python时间处理Python在处理与时间相关的操作时有两个重要模块:time和datetime。在本文中,我们介绍这两个模块并为每个场景
- 方法一.Image { max-width:600px;height:
- 百度AI接口的调用方法不必多介绍。官网地址人流量统计新建AipBodyAnalysisfrom aip import AipBodyAnal
- 说明:本文内容都是从Google上搜索来的,本想上http://www.alexa.com/查官方数据,访问非常慢暂且没查。使用本接口将返回
- 在python开发的过程中,经常会遇到需要打印各种信息。海量的信息堆砌在控制台中,就会导致信息都混在一起,降低了重要信息的可读性。这时候,如
- 设置模板路径在django项目下创建templats文件来存放html文件为了减少模板加载调用过程及模板本身的冗余代码,Django 提供了
- 项目有时要用一些Ajax的效果,因为比较简单,也就没有去用什么Ajax.net之类的东西,手写代码也就实现了。 第二天,有人反馈错
- Python是一种解释型、面向对象、动态数据类型的高级程序设计语言,本文就举一例Python类继承的实例。实例代码如下:#! /usr/bi
- 3月27日,淘宝网获得了由国际权威机构G-CEM颁发的2008年度亚洲区在线客户体验大奖,这是全球互联网企业首次获得此殊荣。如何在让买家更方