非同期タスク処理AsyncTask(Python)の実現
2554 ワード
について
タスクにタグを追加し、タスクが完了すると完了とマークします.タスクが完了すると、タスクの実行結果を直接取得できます.タスクが完了していない場合、タスク結果が取得され、取得スレッドがブロックされます.
主な実装関数運転結果(set_result) の設定実行結果(get_result) を取得
具体的な実装
タスクにタグを追加し、タスクが完了すると完了とマークします.タスクが完了すると、タスクの実行結果を直接取得できます.タスクが完了していない場合、タスク結果が取得され、取得スレッドがブロックされます.
主な実装関数
具体的な実装
# -*- encoding=utf-8 -*-
import time
from operate_system import task, pool
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)
# (wait)
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())
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()