lundi 5 juin 2017

How to get different answers from different threads?

To get to know threading concept better I tried to use threads in a simple program. I want to call a function 3 times which does random selection.

def func(arg):
    lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    num = random.choice(lst)
    arg.append(num)
    return arg


def search(arg):
    a = func(arg)
    a = func(a)
    threads_list = []
    que = queue.Queue()
    for i in range(3):
        t = threading.Thread(target=lambda q, arg1: q.put(func(arg1)), args=(que, a))
        t.start()
        threads_list.append(t)

    for t in threads_list:
        t.join()
    while not que.empty():
        result = que.get()
        print (result)

 if __name__ == '__main__':
     lst = []
     search(lst)

As you can see In the third part, I used threads but I expected to get different lists ( different for the third part). but all the threads return the same answer.
Can anyone help me to get different lists from different threads?
I think I misunderstood the concept of multiprocessing and multithreading.




Aucun commentaire:

Enregistrer un commentaire