Is there a way to exit the other thread based on the value returned from another thread in python?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders
--
Chapters
00:00 Is There A Way To Exit The Other Thread Based On The Value Returned From Another Thread In Python?
01:01 Accepted Answer Score 1
01:51 Thank you
--
Full question
https://stackoverflow.com/questions/4833...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pythonmultithreading
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders
--
Chapters
00:00 Is There A Way To Exit The Other Thread Based On The Value Returned From Another Thread In Python?
01:01 Accepted Answer Score 1
01:51 Thank you
--
Full question
https://stackoverflow.com/questions/4833...
--
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.