I have the code below that I am using to thread certain tasks. Basically, you pass in a function reference, a list of data and the number of threads. It will run the function for each item in the list with the specified number of threads.
I currently have this in a separate py file that I import as needed. Performance has been kind of strange and inconsistent though. What do you guys think?
import threading
import logging
import threading
import time
from queue import Queue
def thread_proc(func,data,threads):
if threads < 0:
return "Thead Count not specified"
q = Queue()
for i in range(threads):
thread = threading.Thread(target=thread_exec,args=(func,q))
thread.daemon = True
thread.start()
for item in data:
q.put(item)
logging.debug('*** Main thread waiting')
s = q.qsize()
while s > 0:
logging.debug("Queue Size is:" + str(s))
s = q.qsize()
time.sleep(1)
logging.debug('*** Main thread waiting')
q.join()
logging.debug('*** Done')
def thread_exec(func,q):
while True:
d = q.get()
#logging.debug("Working...")
try:
func(d)
except:
pass
q.task_done()
multiprocessing.dummy.Pool
which is just likemultiprocessing.pool.Pool
but with threads instead of processes. \$\endgroup\$