1.多线程
多线程和多进程的表现形式差不多
IO密集型用多线程
线程是应用程序中的最小单元
多线程的实现有两种方式:
方法一:
将要执行的方法作为参数传给Thread的构造方法(和多进程类似)
t = threading.Thread(target=action, args=(i,))
方法二:
从Thread继承,并重写run()
看源码:
P = threading.Thread
p.start() -> _start_new_thread(self.__bootstrap, ()) -> self.__bootstrap_inner() -> self.run()
try:
if self.__target:
self.__target(*self.__args, **self.__kwargs)
所以如果重写了run,就直接调用run的函数了,如果run没有重新,就调用target函数。
举例:
import threading
def worker(n):
print ("start worker{0}".format(n))
class MyThread(threading.Thread):
def __init__(self, args):
super(MyThread, self).__init__()
self.args = args
def run(self):
print ("start MyThread{0}".format(self.args))
if __name__ == "__main__":
for i in xrange(1, 6):
t1 = threading.Thread(target=worker, args=(i,))
t1.start()
t1.join()
for x in xrange(6, 11):
t2 = MyThread(x)
t2.start()
t2.join()
返回结果:
start worker1 start worker2 start worker3 start worker4 start worker5 start MyThread6 start MyThread7 start MyThread8 start MyThread9 start MyThread10
多线程锁:
写法与多进程很多都类似
通过threading.Lock()来创建锁,函数在执行的只有先要获得锁,然后执行完以后要释放锁:
with lock: lock.acquire() lock.release()
举例:
import threading
import time
def worker(name, lock):
with lock:
print ("start {0}".format(name))
time.sleep(1)
print ("end {0}".format(name))
if __name__ == "__main__":
lock = threading.Lock()
t1 = threading.Thread(target=worker, args=("worker1",lock))
t2 = threading.Thread(target=worker, args=("worker2",lock))
t1.start()
t2.start()
print ("main end")
返回结果:
start worker1 main end end worker1 start worker2 end worker2
由结果可知:
按依次的顺序来执行,谁先获得这个锁以后谁先来执行,当他执行完毕后,将锁释放掉,下一个函数来执行的时候,才能够获得锁来执行。
转载于:https://blog.51cto.com/286577399/2050404