Skip to content

Commit 7a71693

Browse files
committed
Merge remote-tracking branch 'xianhu/master'
2 parents 6ba9d92 + 9f64177 commit 7a71693

File tree

3 files changed

+173
-2
lines changed

3 files changed

+173
-2
lines changed

README.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
### python_lda.py: 玩点高级的--带你入门Topic模型LDA(小改进+附源码)
1414

15-
### python_sqlalchemy.py: 作为一个Pythoner不会SQLAlchemy都不好意思跟同行打招呼!
15+
### python_sqlalchemy.py: 作为一个Pythoner, 不会SQLAlchemy都不好意思跟同行打招呼!
1616

1717
### python_oneline.py: 几个小例子告诉你, 一行Python代码能干哪些事
1818

@@ -26,9 +26,13 @@
2626

2727
### python_metaclass.py: Python进阶: 一步步理解Python中的元类metaclass
2828

29-
### python_coroutine.py: Python进阶理解Python中的异步IO和协程(Coroutine), 并应用在爬虫中
29+
### python_coroutine.py: Python进阶: 理解Python中的异步IO和协程(Coroutine), 并应用在爬虫中
3030

3131
### python_aiohttp.py: Python中最好用的异步爬虫库Aiohttp代码实例
32+
33+
### python_thread_multiprocess.py: Python进阶: 聊聊IO密集型任务、计算密集型任务,以及多线程、多进程
34+
35+
### python_version36.py: Python3.6正式版要来了, 你期待哪些新特性?
3236
===================================================================================================
3337

3438
### 您可以fork该项目,并在修改后提交Pull request

python_thread_multiprocess.py

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# _*_ coding: utf-8 _*_
2+
3+
"""
4+
python_thread_multiprocee.py by xianhu
5+
"""
6+
7+
import time
8+
import threading
9+
import multiprocessing
10+
11+
# 定义全局变量Queue
12+
g_queue = multiprocessing.Queue()
13+
g_search_list = list(range(10000))
14+
15+
16+
# 定义一个IO密集型任务:利用time.sleep()
17+
def task_io(task_id):
18+
print("IOTask[%s] start" % task_id)
19+
while not g_queue.empty():
20+
time.sleep(1)
21+
try:
22+
data = g_queue.get(block=True, timeout=1)
23+
print("IOTask[%s] get data: %s" % (task_id, data))
24+
except Exception as excep:
25+
print("IOTask[%s] error: %s" % (task_id, str(excep)))
26+
print("IOTask[%s] end" % task_id)
27+
return
28+
29+
30+
# 定义一个计算密集型任务:利用一些复杂加减乘除、列表查找等
31+
def task_cpu(task_id):
32+
print("CPUTask[%s] start" % task_id)
33+
while not g_queue.empty():
34+
count = 0
35+
for i in range(10000):
36+
count += pow(3*2, 3*2) if i in g_search_list else 0
37+
try:
38+
data = g_queue.get(block=True, timeout=1)
39+
print("CPUTask[%s] get data: %s" % (task_id, data))
40+
except Exception as excep:
41+
print("CPUTask[%s] error: %s" % (task_id, str(excep)))
42+
print("CPUTask[%s] end" % task_id)
43+
return task_id
44+
45+
46+
def init_queue():
47+
print("init g_queue start")
48+
while not g_queue.empty():
49+
g_queue.get()
50+
for _index in range(10):
51+
g_queue.put(_index)
52+
print("init g_queue end")
53+
return
54+
55+
56+
if __name__ == '__main__':
57+
print("cpu count:", multiprocessing.cpu_count(), "\n")
58+
59+
print("========== 直接执行IO密集型任务 ==========")
60+
init_queue()
61+
time_0 = time.time()
62+
task_io(0)
63+
print("结束:", time.time() - time_0, "\n")
64+
65+
print("========== 多线程执行IO密集型任务 ==========")
66+
init_queue()
67+
time_0 = time.time()
68+
thread_list = [threading.Thread(target=task_io, args=(i,)) for i in range(5)]
69+
for t in thread_list:
70+
t.start()
71+
for t in thread_list:
72+
if t.is_alive():
73+
t.join()
74+
print("结束:", time.time() - time_0, "\n")
75+
76+
print("========== 多进程执行IO密集型任务 ==========")
77+
init_queue()
78+
time_0 = time.time()
79+
process_list = [multiprocessing.Process(target=task_io, args=(i,)) for i in range(multiprocessing.cpu_count())]
80+
for p in process_list:
81+
p.start()
82+
for p in process_list:
83+
if p.is_alive():
84+
p.join()
85+
print("结束:", time.time() - time_0, "\n")
86+
87+
print("========== 直接执行CPU密集型任务 ==========")
88+
init_queue()
89+
time_0 = time.time()
90+
task_cpu(0)
91+
print("结束:", time.time() - time_0, "\n")
92+
93+
print("========== 多线程执行CPU密集型任务 ==========")
94+
init_queue()
95+
time_0 = time.time()
96+
thread_list = [threading.Thread(target=task_cpu, args=(i,)) for i in range(5)]
97+
for t in thread_list:
98+
t.start()
99+
for t in thread_list:
100+
if t.is_alive():
101+
t.join()
102+
print("结束:", time.time() - time_0, "\n")
103+
104+
print("========== 多进程执行cpu密集型任务 ==========")
105+
init_queue()
106+
time_0 = time.time()
107+
process_list = [multiprocessing.Process(target=task_cpu, args=(i,)) for i in range(multiprocessing.cpu_count())]
108+
for p in process_list:
109+
p.start()
110+
for p in process_list:
111+
if p.is_alive():
112+
p.join()
113+
print("结束:", time.time() - time_0, "\n")
114+
115+
exit()

python_version36.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# _*_ coding: utf-8 _*_
2+
3+
"""
4+
python_version36.py by xianhu
5+
"""
6+
7+
import asyncio
8+
import decimal
9+
from typing import List, Dict
10+
11+
# Formatted string literals
12+
name = "Fred"
13+
print(f"He said his name is {name}.") # 'He said his name is Fred.'
14+
print("He said his name is {name}.".format(**locals()))
15+
16+
width = 10
17+
precision = 4
18+
value = decimal.Decimal("12.34567")
19+
print(f"result: {value:{width}.{precision}}") #'result: 12.35'
20+
21+
22+
# variable annotations
23+
def test(a: List[int], b: int) -> int:
24+
return a[0] + b
25+
print(test([3, 1], 2))
26+
27+
primes: List[int] = []
28+
captain: str
29+
30+
class Starship:
31+
stats: Dict[str, int] = {}
32+
33+
34+
# Underscores in Numeric Literals
35+
a = 1_000_000_000_000_000 # 1000000000000000
36+
b = 0x_FF_FF_FF_FF # 4294967295
37+
38+
'{:_}'.format(1000000) # '1_000_000'
39+
'{:_x}'.format(0xFFFFFFFF) # 'ffff_ffff'
40+
41+
42+
# Asynchronous Generators
43+
async def ticker(delay, to):
44+
"""Yield numbers from 0 to *to* every *delay* seconds."""
45+
for i in range(to):
46+
yield i
47+
await asyncio.sleep(delay)
48+
49+
50+
# Asynchronous Comprehensions
51+
result = [i async for i in aiter() if i % 2]
52+
result = [await fun() for fun in funcs if await condition()]

0 commit comments

Comments
 (0)