个人一直觉得对学习任何知识而言,概念是相当重要的。掌握了概念和原理,细节可以留给实践去推敲。掌握的关键在于理解,通过具体的实例和实际操作来感性的体会概念和原理可以起到很好的效果。本文通过一些具体的例子简单介绍一下python的多线程和多进程,后续会写一些进程通信和线程通信的一些文章。
python多线程
python中提供两个标准库thread和threading用于对线程的支持,python3中已放弃对前者的支持,后者是一种更高层次封装的线程库,接下来均以后者为例。
创建线程
python中有两种方式实现线程:
实例化一个threading.Thread的对象,并传入一个初始化函数对象(initial function )作为线程执行的入口;
继承threading.Thread,并重写run函数;
方式1:创建threading.Thread对象
import threading
import time
def tstart(arg):
time.sleep(0.5)
print("%s running...." % arg)
if __name__ == '__main__':
t1 = threading.Thread(target=tstart, args=('This is thread 1',))
t2 = threading.Thread(target=tstart, args=('This is thread 2',))
t1.start()
t2.start()
print("This is main function")
结果:
This is main function
This is thread 2 running....
This is thread 1 running....
方式2:继承threading.Thread,并重写run
import threading
import time
class CustomThread(threading.Thread):
def __init__(self, thread_name):
# step 1: call base __init__ function
super(CustomThread, self).__init__(name=thread_name)
self._tname = thread_name
def run(self):
# step 2: overide run function
time.sleep(0.5)
print("This is %s running...." % self._tname)
if __name__ == "__main__":
t1 = CustomThread("thread 1")
t2 = CustomThread("thread 2")
t1.start()
t2.start()
print("This is main function")
执行结果同方式1.
threading.Thread
上面两种方法本质上都是直接或者间接使用threading.Thread类
threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
关联上面两种创建线程的方式:
import threading
import time
class CustomThread(threading.Thread):
def __init__(self, thread_name, target = None):
# step 1: call base __init__ function
super(CustomThread, self).__init__(name=thread_name, target=target, args = (thread_name,))
self._tname = thread_name
def run(self):
# step 2: overide run function
# time.sleep(0.5)
# print("This is %s running....@run" % self._tname)
super(CustomThread, self).run()
def target(arg):
time.sleep(0.5)
print("This is %s running....@target" % arg)