同时工作(Concurrency)、编译(Compilation)和多处理(Multiprocessing)是计算机科学中的三个重要概念。
import threading
def worker():
print(f"Thread {threading.current_thread().name} is running")
threads = []
for i in range(5):
t = threading.Thread(target=worker, name=f"Thread-{i}")
threads.append(t)
t.start()
for t in threads:
t.join()
import asyncio
async def async_worker():
print(f"Task {asyncio.current_task().get_name()} is running")
await asyncio.sleep(1)
async def main():
tasks = [asyncio.create_task(async_worker(), name=f"Task-{i}") for i in range(5)]
await asyncio.gather(*tasks)
asyncio.run(main())
import multiprocessing
def worker():
print(f"Process {multiprocessing.current_process().name} is running")
if __name__ == "__main__":
processes = []
for i in range(5):
p = multiprocessing.Process(target=worker, name=f"Process-{i}")
processes.append(p)
p.start()
for p in processes:
p.join()
希望这些信息对你有所帮助!如果有更多具体问题,欢迎继续提问。
领取专属 10元无门槛券
手把手带您无忧上云