Python学习-Day9-并发编程、装饰器

1026-徐同学

发表文章数:41

首页 » Python » 正文

并发编程

Python学习-Day9-并发编程、装饰器
Python学习-Day9-并发编程、装饰器

#single_thread
import time
def worker(n):
    print('函数执行开始于:{}'.format(time.ctime()))
    time.sleep(n)
    print(f'函数执行结束于:{time.ctime()}')

def main():
    print(f'【主函数执行开始于:{time.ctime()}】')
    worker(4)
    worker(2)
    print(f'【主函数执行开始于:{time.ctime()}】')

if __name__ == '__main__':
    main()

【主函数执行开始于:Thu Apr 23 09:48:42 2020】
函数执行开始于:Thu Apr 23 09:48:42 2020
函数执行结束于:Thu Apr 23 09:48:46 2020
函数执行开始于:Thu Apr 23 09:48:46 2020
函数执行结束于:Thu Apr 23 09:48:48 2020
【主函数执行开始于:Thu Apr 23 09:48:48 2020
#mt_1
import time
import _thread

def worker(n):
    print('函数执行开始于:{}'.format(time.ctime()))
    time.sleep(n)
    print(f'函数执行结束于:{time.ctime()}')

def main():
    print(f'【主函数执行开始于:{time.ctime()}】')
    _thread.start_new_thread(worker,(4,))
    _thread.start_new_thread(worker, (2,))
    print(f'【主函数执行开始于:{time.ctime()}】')

if __name__ == '__main__':
    main()

【主函数执行开始于:Thu Apr 23 09:49:54 2020】
【主函数执行开始于:Thu Apr 23 09:49:54 2020

threading模块

import time
import threading

def worker(n):
    print('{}函数执行开始于:{}'.format(threading.current_thread().name,time.ctime()))
    time.sleep(n)
    print(f'{threading.current_thread().name}函数执行结束于:{time.ctime()}')

class MyThread(threading.Thread):
    def __init__(self,func,args):
        threading.Thread.__init__(self)
        self.func = func
        self.args = args

    def run(self):
        self.func(*self.args)


def main():
    print(f'【主函数执行开始于:{time.ctime()}】')
    #_thread.start_new_thread(worker,(4,))
    #_thread.start_new_thread(worker, (2,))

    threads = []
    #t1 = threading.Thread(target=worker,args=(4,))
    t1 = MyThread(worker,(4,))
    threads.append(t1)
    #threads.append(t1)
    #t2 = threading.Thread(target=worker, args=(2,))
    #threads.append(t2)
    t2 = MyThread(worker, (2,))
    threads.append(t2)
    for t in threads:
        t.start()

    for t in threads:
        t.join()
    print(f'【主函数执行开始于:{time.ctime()}】')

if __name__ == '__main__':
    main()

【主函数执行开始于:Thu Apr 23 10:58:47 2020】
Thread-1函数执行开始于:Thu Apr 23 10:58:47 2020
Thread-2函数执行开始于:Thu Apr 23 10:58:47 2020
Thread-2函数执行结束于:Thu Apr 23 10:58:49 2020
Thread-1函数执行结束于:Thu Apr 23 10:58:51 2020
【主函数执行开始于:Thu Apr 23 10:58:51 2020

Python学习-Day9-并发编程、装饰器

import threading
import time
eggs = []
lock = threading.Lock()
def put_egg(n,lst):
    #lock.acquire()
    with lock:
    for i in range(1,n+1):
        time.sleep(random.randint(0,2))
        lst.append(i)
    #lock.release()

def main():
    threads = []

    for i in range(3):
        t = threading.Thread(target=put_egg,args=(5,eggs))
        threads.append(t)

    for t in threads:
        t.start()

    for t in threads:
        t.join()

    print(eggs)

if __name__ == '__main__':
    main()


[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

队列

Python学习-Day9-并发编程、装饰器

import threading
import queue
import time
import random

def producer(data_queue):
    for i in range(5):
        time.sleep(0.5)
        item = random.randint(1,100)
        data_queue.put(item)
        print(f'{threading.current_thread().name}在队列中放入数据项:{item}')

def consumer(data_queue):
    while True:
        try:
            item = data_queue.get(timeout=3)
            print(f'{threading.current_thread().name}从队列中移除了{item}')
        except queue.Empty:
            break
        else:
            data_queue.task_done()
def main():
    q = queue.Queue()
    threads = []
    p = threading.Thread(target=producer,args=(q,))
    p.start()

    for i in range(2):
        c = threading.Thread(target=consumer,args=(q,))
        threads.append(c)

    for t in threads:
        t.start()

    for t in threads:
        t.join()

    q.join()

if __name__ == '__main__':
    main()



Thread-1在队列中放入数据项:54Thread-2从队列中移除了54

Thread-1在队列中放入数据项:26Thread-3从队列中移除了26

Thread-1在队列中放入数据项:30Thread-2从队列中移除了30

Thread-1在队列中放入数据项:98Thread-3从队列中移除了98

Thread-1在队列中放入数据项:12Thread-2从队列中移除了12

multiprocessing多进程模块

Python学习-Day9-并发编程、装饰器

import multiprocessing
import time
def func(n):
    print(f'{multiprocessing.current_process().name}执行开始于:{time.ctime()}')
    time.sleep(n)
    print(f'{multiprocessing.current_process().name}执行结束于:{time.ctime()}')

def main():
    print(f'主函数运行于:{time.ctime()}')
    process = []
    p1 = multiprocessing.Process(target=func,args=(4,))
    process.append(p1)
    p2 = multiprocessing.Process(target=func, args=(2,))
    process.append(p2)
    for p in process:
        p.start()

    for p in process:
        p.join()
    print(f'主函数结束于:{time.ctime()}')

if __name__ == '__main__':
    main()

主函数运行于:Thu Apr 23 15:24:18 2020
Process-1执行开始于:Thu Apr 23 15:24:19 2020
Process-2执行开始于:Thu Apr 23 15:24:19 2020
Process-2执行结束于:Thu Apr 23 15:24:21 2020
Process-1执行结束于:Thu Apr 23 15:24:23 2020
主函数结束于:Thu Apr 23 15:24:23 2020


Python学习-Day9-并发编程、装饰器

装饰器

Python学习-Day9-并发编程、装饰器

函数基础

将函数作为参数传递

Python学习-Day9-并发编程、装饰器
Python学习-Day9-并发编程、装饰器

函数嵌套及跨域访问

Python学习-Day9-并发编程、装饰器
Python学习-Day9-并发编程、装饰器

函数定义装饰器

def p_decorator(func):
    def wrapper(*args,**kwargs):
        return '</p>'+func(*args,**kwargs)+ '</p>'
    return wrapper

@p_decorator
def get_text():
    return '我爱学习'

if __name__ == '__main__':
    print(get_text())

</p>我爱学习</p>

类数定义装饰器

class P:
    def __init__(self,func):
        self.func = func

    def __call__(self, *args, **kwargs):
        return '<p>'+self.func(*args, **kwargs)+'</p>'
def p_decorator(func):
    def wrapper(*args,**kwargs):
        return '</p>'+func(*args,**kwargs)+ '</p>'
    return wrapper

@P
def get_text():
    return '我爱学习'

if __name__ == '__main__':
    print(get_text())

<p>我爱学习</p>

装饰器参数

class P:
    def __init__(self,func):
        self.func = func

    def __call__(self, *args, **kwargs):
        return '<p>'+self.func(*args, **kwargs)+'</p>'
def p_decorator(func):
    def wrapper(*args,**kwargs):
        return '</p>'+func(*args,**kwargs)+ '</p>'
    return wrapper

@P
def get_text():
    return '我爱学习'

if __name__ == '__main__':
    print(get_text())

<p>我爱学习</p>

未经允许不得转载:作者:1026-徐同学, 转载或复制请以 超链接形式 并注明出处 拜师资源博客
原文地址:《Python学习-Day9-并发编程、装饰器》 发布于2020-04-23

分享到:
赞(0) 打赏

评论 抢沙发

评论前必须登录!

  注册



长按图片转发给朋友

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

Vieu3.3主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。

登录

忘记密码 ?

您也可以使用第三方帐号快捷登录

Q Q 登 录
微 博 登 录