0

This is my code:

import threading
import requests


class MyThread(threading.Thread):
    def __init__(self, id):
        threading.Thread.__init__(self)
        self.id = id

    def run(self):
        print('Thread {0} is running...'.format(self.id))

        req = requests.post(url='http://test.com', data={'id': id})
        if req.json()['success']:
            # stop other threads

        print('Thread {0} is finished!'.format(self.id))


for id in range(0, 480):
    t = MyThread(id)
    t.start()

In every thread I send lots of requests. I want to stop other threads which are made in for loop, if the condition was true.

How to do that?!

Mahdi
  • 73
  • 1
  • 7
  • See http://stackoverflow.com/a/41878713/3901060 for an example of using a `threading.Event` to control multiple threads. – FamousJameous Mar 10 '17 at 20:54
  • Events might not make sense in you case, though. At what point in the `run` function do you expect the to-be-stopped threads to be? Is there a place where you could add an Event check? – FamousJameous Mar 10 '17 at 21:03
  • @FamousJameous I just want to stop all other threads when "if req.json()['success']" is true. – Mahdi Mar 11 '17 at 11:52
  • Threads aren't really meant to be killed externally. That is why you would generally use events to tell the thread to stop itself. You could still use an event and check it at the beginning of `run`. I don't know enough about the threading mechanism to say that that would definitely work, but even if it did it still wouldn't kill all currently running threads. You might want to look into using coroutines instead. Specifically [wait](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait) with `return_when=FIRST_COMPLETED`. – FamousJameous Mar 13 '17 at 16:45

0 Answers0