创建一个线程:
# 方式一
from threading import Thread import time def func(n): time.sleep(1) print(n) t = Thread(target=func, args=(1,)) t.start()
# 方式二 from threading import Thread import time class MyThread(Thread): def __init__(self,n): super().__init__() self.n = n def run(self): time.sleep(1) print(self.n) t = MyThread(1) t.start()
创建多线程:
from threading import Thread import time class MyThread(Thread): def __init__(self,n): super().__init__() self.n = n def run(self): time.sleep(1) print(self.n) for i in range(10): t = MyThread(i) t.start()
from threading import Thread import time def func(n): time.sleep(1) print(n) for i in range(10): t = Thread(target=func, args=(i,)) t.start()
一个进程中的线程数据是共享的:
from threading import Thread import os def func(args): global n n = 0 print(n, os.getpid()) n = 100 t_list = [] for i in range(10): t = Thread(target=func, args=(i,)) t.start() t_list.append(t) for t in t_list: t.join() print(n)
另一种情况:
from threading import Thread import os,time def func(args): global n n = args time.sleep(0.1) print(n, os.getpid()) n = 100 t_list = [] for i in range(10): t = Thread(target=func, args=(i,)) t.start() t_list.append(t) for t in t_list: t.join() print(n)
看到结果都变成一样的了,因为每个线程都将n的值变一次,不管变几次,n最终只有一个值,所在在0.1秒之后在输出n,都输出n的值了,就变成一样的了。
这种情况就会导致数据不安全,因为我不想要同一个输出结果,我想每个线程更改数据都要输出结果,加锁就可以了。
如下:
from threading import Thread, Lock import os,time def func(args, lock): lock.acquire() global n n = args time.sleep(0.1) print(n, os.getpid()) lock.release() lock = Lock() n = 100 t_list = [] for i in range(1000): t = Thread(target=func, args=(i, lock)) t2 = Thread(target=func, args=(i, lock)) t.start() t2.start() t_list.append(t) t_list.append(t2) for t in t_list: t.join() print(n)
这样每个线程的结果都不一样了。
多线程的效率问题:
from threading import Thread import time from multiprocessing import Process def func(n): n += 1 if __name__ == "__main__": t1 = time.time() t_list = [] for i in range(50): t = Thread(target=func, args=(i,)) t.start() t_list.append(t) for t in t_list: t.join() t2 = time.time() - t1 t3 = time.time() p_list = [] for i in range(50): p = Process(target=func, args=(i,)) p.start() p_list.append(p) for p in p_list: p.join() t4 = time.time() - t3 print(t2, t4)
打印结果:
0.007979869842529297 3.0359175205230713
起50个线程的时间远比起50个进程的时间短。