Lesson 43 of 55 · Python
Concurrency with threading
Duration: 20 minutes
Lesson 43 of 55 · Python
Duration: 20 minutes
threading module lets you run multiple threads in the same process, which is handy for I/O‑bound tasks such as network requests or file operations.\n\npython\nimport threading\nimport time\n\ndef worker(name):\n print(f'Thread {name} starting')\n time.sleep(2)\n print(f'Thread {name} finished')\n\nthreads = []\nfor i in range(3):\n t = threading.Thread(target=worker, args=(i,))\n threads.append(t)\n t.start()\n\n# Wait for all threads to finish\nfor t in threads:\n t.join()\n\nprint('All threads completed')\n\n\nBecause of the Global Interpreter Lock (GIL), threading is best suited for I/O‑bound work; for CPU‑heavy tasks you’ll want multiprocessing.\n