The code flow is something as below.
result = []
def Discover(myList=[]):
for item in myList:
t = threading.Thread(target=myFunc, Args=[item])
t.start()
def myFunc(item):
result.append(item+item)
Now this will start multiple threads and in current scenario the threads does some memory intensive Tasks. Thus I want to include semaphores in this so that myList behaves as a queue and number of threads must be in a limited size. What is the better way to do that?
Never use mutable objects as default parameter value in function definition. In your case:
def Discover(myList=[])Use
Queue.Queueinstead oflistto providemyListif it’s necessary to update list of “tasks” when threads are running. Or… Usemultiprocessing.pool.ThreadPoolin order to limit number of running threads at the same time.Use
Queue.Queueinstead oflistto provideresultsvariable.listimplementation is not thread-safe, so you probably will get many problems with it.You can find some examples in other SO questions, i.e. here.
P.S.
ThreadPoolavailable in Python 2.7+