线程与进程都是虚拟单位,,都是用来帮助我们形象的描述某种事物
进程:资源单位(车间)
线程:执行单位(流水线)
将内存比如成工厂 那么进程就相当于是工厂里面的车间 而你的线程就相当于是车间里面的流水线
每一个进程中都会自带一个线程,线程才是真正的执行单位,进程只是在线程运行过程中提供代码运行所需要的资源
开一个进程:
申请一个内存空间 耗时
将代码拷贝到内存空间 耗时
开一个线程:
不需要申请内存空间
一个进程内可以起多个线程,并且线程与线程之间数据是共享的 ps:开启线程的开销要远远小于开启进程的开销
第一种:
from threading import Thread import time def task(name): print(‘%s is running‘%name) time.sleep(2) print(‘%s is over‘%name) t = Thread(target=task,args=(‘egon‘,)) t.start() print(‘主‘)
第二种:
from threading import Thread import time class MyThread(Thread): def __init__(self,name): super().__init__() self.name = name def run(self): print(‘%s is running‘%self.name) time.sleep(3) print(‘%s is over‘%self.name) t = MyThread(‘egon‘) t.start() print(‘主‘)
from threading import Thread,current_thread,active_count import time import os def task(name,i): print(‘%s is running‘%name) # print(‘子current_thread:‘,current_thread().name) # print(‘子‘,os.getpid()) time.sleep(i) print(‘%s is over‘%name) t = Thread(target=task,args=(‘egon‘,1)) # 告诉操作系统开辟一个线程 线程的开销远远小于进程 t1 = Thread(target=task,args=(‘jason‘,2)) t.start() t1.start() t1.join() print(‘当前正在活跃的线程数‘,active_count()) print(‘主‘) # print(‘主current_thread:‘,current_thread().name) # current_thread能够获取当前线程号 # print(‘主‘,os.getpid())
无论是进程还是线程,都遵循:守护xx会等待主xx运行完毕后被销毁。需要强调的是:运行完毕并非终止运行
1.对主进程来说,运行完毕指的是主进程代码运行完毕 2.对主线程来说,运行完毕指的是主线程所在的进程内所有非守护线程统统运行完毕,主线程才算运行完毕
from threading import Thread import time def foo(): print(123) time.sleep(1) print("end123") def bar(): print(456) time.sleep(3) print("end456") t1=Thread(target=foo) t2=Thread(target=bar) t1.daemon=True t1.start() t2.start() print("main-------")
from threading import Thread money = 666 def task(): global money money = 999 t = Thread(target=task) t.start() t.join() # 等待子线程结束 print(money) # 打印结果:999 说明线程用的是同一个资源
from threading import Thread,Lock import time n = 100 def task(): global n tmp = n time.sleep(0.1) n = tmp - 1 t_list = [] for i in range(100): t = Thread(target=task) t.start() t_list.append(t) for t in t_list: t.join() # 打印结果:99
from threading import Thread,Lock import time n = 100 def task(mutex): global n mutex.acquire() # 抢锁 tmp = n time.sleep(0.1) n = tmp - 1 mutex.release() # 释放锁 t_list = [] mutex = Lock() for i in range(100): t = Thread(target=task,args=(mutex,)) t.start() t_list.append(t) for t in t_list: t.join() print(n)
原文:https://www.cnblogs.com/xiongying4/p/11342236.html