Python学习日志002-多进程、多线程、协程-02
'''=================================================
@Project -> File :Residue_processing -> python-003.py
@IDE :PyCharm
@Author :Xue-Qiang Fan
@Date :2020/3/22 11:22
@Describe :多进程,多线程,协程
=================================================='''
from multiprocessing import Queue
from multiprocessing import Process
from time import sleep
q = Queue(5)
q.put('A')
q.put('B')
q.put('C')
q.put('D')
q.put('E')
print(q.qsize())
if not q.full():
q.put('F',timeout=3)
else:
print('队列满了')
print(q.get())
def download(q):
images = ['girl.jpg', 'boy.jpg', 'man.jpg']
for image in images:
print('正在下载', image)
sleep(0.5)
q.put(image)
pass
def getfile(q):
while True:
file = q.get()
print('{}保存成功!'.format(file))
if __name__ == '__main__':
q = Queue(5)
p1 = Process(target=download, args=(q,))
p2 = Process(target=getfile,args=(q,))
p1.start()
p1.join()
p2.start()
p2.join()
'''
线程:线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。
一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
在Unix也被称为轻量进程(lightweight processes),但轻量进程更多指内核线程(kernel thread),
'''
import threading
def download(n):
images = ['girl.jpg', 'boy.jpg', 'man.jpg']
for image in images:
print('正在下载', image)
sleep(n)
pass
def getfile(q):
while True:
file = q.get()
print('{}保存成功!'.format(file))
if __name__ == '__main__':
t = threading.Thread(target=download, args=(1,))
t1 = threading.Thread(target=download, args=(2,))
t.start()
t1.start()
'''
线程同步:一个一个完成
'''
import threading
import random
import time
lock = threading.Lock()
list1 = [0]*10
def task1():
lock.acquire()
for i in range(len(list1)):
list1[i] = 1
time.sleep(0.5)
lock.release()
def task2():
lock.acquire()
for i in range(len(list1)):
print('----', list1[i])
time.sleep(0.5)
lock.release()
if __name__ == '__main__':
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t2.start()
t1.start()