Is there a way to exit the other thread based on the value returned from another thread in python?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles
--
Chapters
00:00 Question
01:19 Accepted answer (Score 1)
02:29 Thank you
--
Full question
https://stackoverflow.com/questions/4833...
Accepted answer links:
[Event Objects]: https://docs.python.org/3/library/thread...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pythonmultithreading
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles
--
Chapters
00:00 Question
01:19 Accepted answer (Score 1)
02:29 Thank you
--
Full question
https://stackoverflow.com/questions/4833...
Accepted answer links:
[Event Objects]: https://docs.python.org/3/library/thread...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pythonmultithreading
#avk47
ACCEPTED ANSWER
Score 1
You can use Event Objects from threading.
You'll need to set an event object in your main method and use it as argument:
def main()
# Initialise thread object
flag = threading.Event()
start t1 # pass flag as arg
start t2 # pass flag as arg
t1.join
t2.join
And your threading logic should be something like this
t1
if (condition is true):
flag.set()
t2
while (not flag.is_set()):
# Logic
return
Here's another real, non-pseudo example
import threading
def main():
# Initialise thread object
flag = threading.Event()
for i in range(2):
if i == 0:
t1 = threading.Thread(target=t1_func, args=(flag,))
t1.start()
else:
t2 = threading.Thread(target=t2_func, args=(flag,))
t2.start()
def t1_func(flag):
for i in range(100000000):
if i == 100000000 - 1:
flag.set()
def t2_func(flag):
while not flag.is_set():
print('not flag yet')
print('GOT FLAG !')
if __name__ == '__main__':
main()
not flag yet
not flag yet
not flag yet
GOT FLAG !
Hope that's helpful and clear.