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

更多python中通过threading模块定义和调用线程相关文章请关注php中文网!

Posted in 未分类

发表评论