Complete remaining threads

How can I kill leftover threads in the middle of assignments in python? example code:

q = Queue.Queue(maxsize=0)
threads = []
max_thread = 10
locker = threading.Semaphore(value=max_thread)
try :
    for user in users_list:
    t = threading.Thread(target=my_function, args=(user,))
    t.setDaemon(True)
    threads.append(t)
    t.start()
    for thread in threads:
        q.put(thread)
    q.join()
except Exception as errtxt:
    print errtxt

      

the function is for example used in thread pools, in this function I want to collect only 30 users with pay more than 5000

def my_function(user):
    locker.acquire()
    if (user.payment > 5000 ):
       collected_users.append(user.id)
       if(len(collected_users) >= 30 :
           return # <- here i wanna kill other remained threads 

    q.task_done()
    locker.release()

      

I think I should set the controller in the queue /

+3


source to share


1 answer


I tried to find a solution for my problem and this is my code: hope someone does it better



import Queue , threading 

q = Queue.Queue(maxsize=0)
threads = []
max_thread = 10
exitFlag = False
users_id = []
collected_users = []

queueLock = threading.Lock()

for x in range(1,50):
    users_id.append(x)

def my_function():
    if not q.empty():
       ids = q.get()
       print (ids)
       if (ids < 5000 ):
            collected_users.append(ids)
       if(len(collected_users) >= 10) :
            print ("collected")
            exitFlag = True
            q.queue.clear()
            q.task_done()
       else:
            q.task_done()
            return
try :
    for ids in users_id:
        q.put(ids)
    while not q.empty():
        queueLock.acquire()
        for workers in range(max_thread):
            t = threading.Thread(target=my_function)
            t.setDaemon(True)
            t.start()
            threads.append(t)
        for t in threads:
            t.join()
        queueLock.release()
        if (exitFlag == True):
            break

   print ("All jobs finished")
except Exception as errtxt:
   print errtxt

      

0


source







All Articles