day9、进程-线程-协程

1_单任务

from time import sleep

def run():
    print("你好!有空吗?")

if __name__ == '__main__':
    while True:
        print("Hello,Are you free?")
    # 现在main和run两个任务是串行的,即是单任务
    run()

2_用多进程多任务

from multiprocessing import  Process
from time import sleep
import os

# 定义一个函数
def run():
    while True:
        print("当前进程:",os.getpid())
        print("我是子进程!")
        sleep(2)

if __name__ == '__main__':
    print("主进程:",os.getpid())
    # 让这两个任务,多进程并发执行
    # 给run创建一个子进程
    p = Process(target=run)
    p.start()
    while True:
        print("are you OK?我是主进程!")
        sleep(1)

3_开启线程

import threading,time


def run(num):
    while True:
        print("当前子线程为%s"%threading.current_thread().name)
        time.sleep(1)
        print("打印",num)

if __name__ == '__main__':


    # run(1)
    # 开启一个子线程
    t = threading.Thread(target=run,name="runTread",args=(1,))
    # 开启线程
    t.start()

    while True:
        print("我是主线程")
        print("主线程(%s)启动" % (threading.current_thread().name))
        time.sleep(1)

4_线程之间的数据共享

import threading
import time
'''
多线程和多进程之间主要区别,多进程中同一变量各自有一份拷贝副本存在于每个进程中,互不影向。而多线程中,所有的变量都是共享。任何一个变量都可以被任何一个子线程修改,这种线程之间数据共享的情况的最大危险在于,如果多个线程同时修改同一个变量,就会造成很多的错乱。
'''
num = 0
def run(n):
    global num
    for i in range(10000):
        num += n
        print(num)
        num -= n
        time.sleep(0.1)


if __name__ == '__main__':
    t1 = threading.Thread(target=run,args=(6,))
    t2 = threading.Thread(target=run,args=(9,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print("num=",num)

5_线程锁

'''
多个线程共享同一个数据会造成数据的读写错乱

解决问题:线程加锁
'''

import threading

lock = threading.Lock()

num = 0

def run(n):
    global  num

    for i in range(100):
        # print(num)
        lock.acquire()
        try:
            num = num + n
            print(num)
            num = num - n
        finally:
            lock.release()


if __name__ == '__main__':
    t1 = threading.Thread(target=run,args=(8,))
    t2 = threading.Thread(target=run,args=(10,))
    t1.start()
    t2.start()
    t1.join()
    t2.join() # 把线程加入线程队列进行管理
    print(num)

6_协程

# 子程序调用
'''
def C():
    print("C_start")
    print("C-end")

def B():
    print("B_start")
    C()
    print("B-end")

def A():
    print("A-start")
    B()
    print("A-end")

A()
'''
# 生成器
# 生成器中每一个yield代表一个代码段,通过迭代这个生成器可以选择去执行哪一个代码段
def run():
    print(1)
    yield 10
    print(2)
    yield 20
    print(3)
    yield 30

m = run() # 调用run的时候run没有真正的执行,而是把他内部一个又一个的yield,创建对应的协程存储到生成器中
# 当我们迭代遍历该生成器的时候,迭代到那一段就会执行这一段
print(m) # 
print(next(m))
a =next(m)
next(m)

7_协程数据传输

def run():
    # 定义一个变量data
    data = ""
    r = yield data
    print(1,r,data)
    r = yield "aa"
    print(2,r,data)
    r = yield "bb"
    print(3,r,data)
    y = yield "cc"

m = run()
# print(m)
print(m.send(None))
print(m.send("a"))
print(m.send('b'))
print(m.send('c'))

8_协程案例

import time

def buy():
    result = ""
    while True:
        n = yield result
        if not n:
            return None
        time.sleep(1)
        result = "{n}购买成功".format(n=n)


def make(buy):
    next(buy)
    n = 0
    while n < 5:
        n = n + 1
        r = buy.send(n)
        print(r)
    buy.close()
if __name__ == '__main__':
    buy = buy()
    make(buy)

9_异步协程

import asyncio

# 创建一个类,做汉堡类
class Hamburger(object):
    @classmethod
    def make(cls,n,*args,**kwargs):
        # 创建指定的对象
        hamburgers = []
        for i in range(n):
            # 创建对象
            hamburgers.append(cls.__new__(cls,*args,**kwargs))
        return hamburgers
# 创建5个实例,每一个实例相当于一个汉堡
hamburgers = Hamburger.make(12)
print(hamburgers)

async def make_hamburgers(n):
    # 定义一个变量用于统计汉堡的个数
    count = 0
    while True:
        if len(hamburgers) == 0:
            # 如果没有,根据请求来做汉堡
            await ask_for_hamburgers()
            pass
        # 取出一个汉堡给客户
        h = hamburgers.pop()
        asyncio.sleep(2)
        yield h
        count += 1
        # 如果n个汉堡都做完了结束循环
        if count == n:
            break
# 定义个函数用于做汉堡
async def ask_for_hamburgers():
    await asyncio.sleep(3)
    hamburgers.extend(Hamburger.make(8))

# 定义一个函数来买汉堡
async def buy_hamburgers():
    b = []
    async for h in make_hamburgers(12):
        b.append(h)
        print("买到第{0}个汉堡".format(id(h)))

# 开启异步循环
loop = asyncio.get_event_loop()
loop.run_until_complete(buy_hamburgers())
loop.close()

你可能感兴趣的:(day9、进程-线程-协程)