from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from time import sleep, time
def party_later(kind='', n=''):
sleep(3)
return kind + n + ' party time!: ' + __name__
def main():
with ProcessPoolExecutor() as proc_executor:
with ThreadPoolExecutor() as thread_executor:
start_time = time()
proc_future1 = proc_executor.submit(party_later, kind='proc', n='1')
proc_future2 = proc_executor.submit(party_later, kind='proc', n='2')
thread_future1 = thread_executor.submit(party_later, kind='thread', n='1')
thread_future2 = thread_executor.submit(party_later, kind='thread', n='2')
for f in as_completed([
proc_future1, proc_future2, thread_future1, thread_future2,]):
print(f.result())
end_time = time()
print('total time to execute four 3-sec functions:', end_time - start_time)
if __name__ == '__main__':
main()
此脚本的输出示例:
thread1 party time!: __main__
thread2 party time!: __main__
proc1 party time!: __mp_main__
proc2 party time!: __mp_main__
total time to execute four 3-sec functions: 3.4519670009613037
在一个线程中,我建议sleep function:
这个函数实际上暂停了操作系统调用它的线程的处理,允许其他线程和进程在它休眠时执行。
为此目的使用它,或者只是延迟函数的执行。例如:
“万岁!”在我按下回车键3秒后打印。
对多个线程和进程使用
sleep
的示例同样,
sleep
挂起您的线程-它几乎使用零处理能力。要演示,请创建这样的脚本(我首先在交互式Python 3.5shell中尝试了此操作,但子进程由于某些原因找不到
party_later
函数):此脚本的输出示例:
多线程
您可以使用
Timer
threading对象触发稍后在单独线程中调用的函数:空行显示了打印到标准输出的函数,我必须按回车以确保出现提示。
这种方法的优点是,当
Timer
线程在等待时,我可以做其他事情,在本例中,在函数执行之前按一次EnterEnter。multiprocessing library中没有相应的对象。你可以创建一个,但它可能不存在的原因。对于一个简单的计时器来说,子线程比一个全新的子进程更有意义。
下面是另一个例子,大约每分钟运行一次:
您可以使用^{} function in the ^{} module 。对于亚秒分辨率,它可以采用浮点参数。
相关问题 更多 >
编程相关推荐