单线程案例
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()
结果是:
【函数执行开始于:Fri Nov 8 10:26:11 2019】
函数执行开始于:Fri Nov 8 10:26:11 2019
函数执行结束于:Fri Nov 8 10:26:15 2019
函数执行开始于:Fri Nov 8 10:26:15 2019
函数执行结束于:Fri Nov 8 10:26:17 2019
【函数执行结束于:Fri Nov 8 10:26:17 2019】
放鸡蛋案例
import threading
import time
eggs = []
def put_eggs(n, lst):
for i in range(1, n + 1):
lst.append(i)
def main():
threads = []
for i in range(3):
t = threading.Thread(target=put_eggs, args=(5, eggs))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
print(eggs)
结果是:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
import threading
import time
import random
eggs = []
lock = threading.Lock()
def put_egg(n, lst):
for i in range(1, n + 1):
time.sleep(random.randint(0, 2))
lst.append(i)
def main():
threads = []
for i in range(3):
t = threading.Thread(target=put_eggs, 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, 1, 2, 1, 3, 4, 5, 3, 2, 3, 4, 4, 5, 5]
加锁放鸡蛋案例
import threading
import time
import random
eggs = []
lock = threading.Lock()
def put_egg(n, lst):
lock.acquire()
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]
放鸡蛋加锁的第二种方法
import threading
import time
import random
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]
先进先出法
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 在队列中放入数据项:30
Thread-2从队列中移除了30
Thread-1 在队列中放入数据项:28
Thread-3从队列中移除了28
Thread-1 在队列中放入数据项:1
Thread-2从队列中移除了1
Thread-1 在队列中放入数据项:59
Thread-3从队列中移除了59
Thread-1 在队列中放入数据项:64
Thread-2从队列中移除了64
装饰器
第一种方法:
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())
结果是:
欢迎来到冰封王国
***args,kwargs:代表任意函数的任意字符串
第二种方法:
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__':
html = p_decorator(get_text)
print(html())
结果是:
欢迎来到冰封王国
返回大写的装饰器
def p_decorator(func):
def wrapper(*args, **kwargs):
return "<p>" + func(*args, **kwargs) + "</p>"
return wrapper
# @p_decorator
def get_text():
return "欢迎来到冰封王国"
@p_decorator
def get_upper_text(text):
return text.upper()
if __name__ == '__main__':
print(get_upper_text("www.asasadsdsds.com"))
结果是:
WWW.ASASADSDSDS.COM
定义类装饰器
class P:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return "<p>" + self.func(*args, **kwargs) + "</p>"
@P
def get_text():
return "欢迎学习"
@P
def get_upper_text(text):
return text.upper()
if __name__ == '__main__':
print(get_upper_text("www.asadsds.com"))
结果是:
WWW.ASADSDS.COM
def p_decorator(func):
def wrapper(*args, **kwargs):
return "<p>" + func(*args, **kwargs) + "</p>"
return wrapper
class Student:
def __init__(self, name):
self.name = name
@p_decorator
def get_name(self):
return self.name.upper()
# @p_decorator
def get_text():
return "欢迎来到冰封王国"
@p_decorator
def get_upper_text(text):
return text.upper()
if __name__ == '__main__':
s = Student("mike")
print(s.get_name())
结果是:
MIKE
参数装饰器
def p_decorator(func):
def wrapper(*args, **kwargs):
return "<div>{}</div>".format(func(*args, **kwargs))
return wrapper
return wrapper
class Student:
def __init__(self, name):
self.name = name
@p_decorator
def get_name(self):
return self.name.upper()
@p_decorator
def get_text():
return "欢迎来到冰封王国"
@p_decorator
def get_upper_text(text):
return text.upper()
if __name__ == '__main__':
print(get_upper_text("www.jkajsjhdshd.com"))
结果是:
# 参数化装饰器
def tags(tag):
def tag_decorrator(func):
def wrapper(*args, **kwargs):
return f"<{tag}>{func(*args, **kwargs)}</{tag}>"
return wrapper
return tag_decorrator
def p_decorator(func):
def wrapper(*args, **kwargs):
return "<div>{}</div>".format(func(*args, **kwargs))
return wrapper
return wrapper
class Student:
def __init__(self, name):
self.name = name
@p_decorator
def get_name(self):
return self.name.upper()
def get_text():
return "欢迎来到冰封王国"
@tags("boy")
@tags("div")
def get_upper_text(text):
return text.upper()
if __name__ == '__main__':
print(get_upper_text("www.jkajsjhdshd.com"))
结果是: