python简说(二十九)线程,进程

进程:
一些资源的集合。
一个进程里面最少有一个线程,主线程。
线程:
程序执行的最小单位。
import threading
from threading import Thread
import time
先执行主线程
def run():
time.sleep(1)
print('run...')


start_time = time.time()

# for i in range(5): #串行
# run()

# threads = []

for i in range(20):
t1 = Thread(target=run,)
t1.start()

# threads.append(t1)

# for t in threads:等待所有的线程
# t.join()
# t1.join()#主线程等待子线程执行结束,只等最后一个线程

while threading.active_count()!=1: #判断子线程是否执行结束
pass

end_time = time.time()

print(end_time - start_time)

#多线程
for url in urls:
t = threading.Thread(target=down_load_pic,args=(url,) ) 注意参数
t.start()


def down_load_pic(url):
#下载图片的url
r = requests.get(url)
file_name = md5(r.content).hexdigest()#把文件md5之后字符串当做文件名
with open(file_name+'.jpg','wb') as fw:
fw.write(r.content)
print('%s下载完成'%file_name)
res.append(file_name)
想要返回值,只能定义一个list
 

电脑CPU有几个核心,就同时只能运行几个任务。

#上下文切换,cpu运行快,切换速度快

python,全局解释器锁,GIL,只能在一个cpu上运行

多个线程同时去操作同一个数据的时候,可能会导致数据不正确。
要把这个数据机上锁,这样同时就只能有一个线程在操作这个数据了。
import threading

count = 0

lock = threading.Lock() #申请一把锁

def run():
global count
with lock:
count+=1
# lock.acquire()#加上锁
# count+=1
# lock.release()#释放

for i in range(10):
t = threading.Thread(target=run)
t.start()

while threading.active_count()!=1:
pass

print(count)

守护线程:
守护主线程,主线程执行完成之后,子线程立即结束。

import threading
import time
def run():
time.sleep(5)
print('run。。。')

for i in range(100):
puren = threading.Thread(target=run)
puren.setDaemon(True)#设置子线程为守护线程
puren.start()

print('over')

多线程

多进程
可以利用多个cpu的。

IO密集型任务
IO消耗比较多的
多线程
input output
磁盘io
网络io

CPU密集型任务
消耗CPU多的,多线程
import multiprocessing
import time
import threading
import requests
def run():
time.sleep(10)
print('run...')

if __name__ == '__main__':
for i in range(10):
p = multiprocessing.Process(target=run)
p.start()
while multiprocessing.active_children(): #等待其他子进程运行结束
pass
posted @ 2019-01-15 20:01  狐觞  阅读(187)  评论(0编辑  收藏  举报