-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
85 lines (81 loc) · 2.51 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# _*_ encoding=utf-8 _*_
#测试用例
from python线程池 import task,pool
import time
class SimpleTask(task.Task):
def __init__(self,callable):
super(SimpleTask,self).__init__(callable)
def process():
time.sleep(1)
print("This is a SimpleTask callable function 1")
time.sleep(1)
print("This is a SimpleTask callable function 2")
def test():
#1.初始化一个线程池
test_pool=pool.ThreadPool()
test_pool.start()
#2.生成一系列的任务
for i in range(10):
simple_task=SimpleTask(process)
#3.往线程池提交任务执行
test_pool.put(simple_task)
pass
def test_async_task():
def async_process():
num=0
for i in range(100):
num+=i
return num
#1.初始化一个线程池
test_pool=pool.ThreadPool()
test_pool.start()
#2.生成一系列的任务
for i in range(10):
async_task=task.AsyncTask(func=async_process)
test_pool.put(async_task)
result=async_task.get_result()
print("Get result: %d"%result)
#测试是否可以真正的等待
def test_async_task2():
def async_process():
num=0
for i in range(100):
num+=i
time.sleep(5)
return num
#1.初始化一个线程池
test_pool=pool.ThreadPool()
test_pool.start()
#2.生成一系列的任务
for i in range(1):
async_task=task.AsyncTask(func=async_process)
test_pool.put(async_task)
print("get result in timestamp: %d"%time.time())
time.sleep(5)
result=async_task.get_result()
print("get result in timestamp: %d :%d"%(time.time(),result))
#测试没有等待是否也可以正常获取结果
def test_async_task3():
def async_process():
num=0
for i in range(100):
num+=i
return num
#1.初始化一个线程池
test_pool=pool.ThreadPool()
test_pool.start()
#2.生成一系列的任务
for i in range(1):
async_task=task.AsyncTask(func=async_process)
test_pool.put(async_task)
print("get result in timestamp: %d"%time.time())
# time.sleep(5)
#转而去处理别的逻辑也是可以的,等到某一时刻我们需要结果了,我们再把结果取出来
#这样子就实现了任务的异步处理。
result=async_task.get_result()
print("get result in timestamp: %d :%d"%(time.time(),result))
if __name__ == "__main__":
# test()
# test_async_task()
# test_async_task2()
test_async_task3()