Created
April 3, 2021 02:21
-
-
Save ma7dev/6b0ea0c5d26c218b691bc37b1cdce81e to your computer and use it in GitHub Desktop.
Multi-threading skeleton code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"metadata": { | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": 3 | |
}, | |
"orig_nbformat": 2 | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2, | |
"cells": [ | |
{ | |
"source": [ | |
"## Question\n", | |
"\n", | |
"How to use multiple threads to run a python function?\n", | |
"\n", | |
"## Answer" | |
], | |
"cell_type": "markdown", | |
"metadata": {} | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import threading\n", | |
"\n", | |
"NUM_THREADS = 16\n", | |
"\n", | |
"# this function will be passed to every thread to be run\n", | |
"def request_thread(a,b, lock):\n", | |
" print('I am thread number %s'%(threading.current_thread().name))\n", | |
"\n", | |
" lock.acquire()\n", | |
" thread_name = threading.current_thread().name\n", | |
" print('Thread %s has acquired the lock'%(thread_name))\n", | |
" # START: WHERE YOU HAVE THE MULTITHREADING TASK\n", | |
" # ...\n", | |
" # END:\n", | |
" lock.release()\n", | |
"\n", | |
"threads = []\n", | |
"locks = []\n", | |
"for i in range(NUM_THREADS):\n", | |
" # create a new list for every thread\n", | |
" results_thread.append([])\n", | |
" # create a locker to control the thread for every thread\n", | |
" locks.append(threading.Lock())\n", | |
"\n", | |
" # add the thread process to threads list to be run later\n", | |
" threads.append(threading.Thread(target=request_thread, args=(a,b, locks[i],))) # you can add more parameters, but you will need to have locks[i]\n", | |
"\n", | |
"# start the multithreading process\n", | |
"for t in threads: t.start()\n", | |
"\n", | |
"# wait until all threads are completed\n", | |
"for t in threads: t.join()\n", | |
"\n", | |
"# add whatever you want after\n", | |
"# ..." | |
] | |
}, | |
{ | |
"source": [ | |
"This format of answers was inspired by [@HamelHusain](https://twitter.com/HamelHusain)'s [tweet](https://twitter.com/HamelHusain/status/1377665676458946561)" | |
], | |
"cell_type": "markdown", | |
"metadata": {} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment