My application needs to run a function and a thread concurrently . I have created a thread inside a function and start the thread. I try to run both the function and thread concurrently and i want to stop the thread until some conditions gets satisfied inside the function. But the thread runs first until its completion and then only the function starts executing. I cant able to achieve the concurrency.
This is my code
import threading
from time import sleep
start_threads = False
stop_threads = True
def testthread():
global stop_threads
k = 0
while k < 100:
print("testthread -->",k)
k = 1
sleep(1)
if k == 100:
stop_threads = True
if stop_threads:
break
def testfunction():
global stop_threads
t1 = threading.Thread(target = testthread)
t1.start()
i = 0
while i < 100:
print("testfunction-->",i)
i = 1
sleep(1)
if i == 100:
stop_threads = False
if stop_threads:
t1.join()
print('thread killed')
testfunction()
i tried to get the output like....
testthread --> 0
testthread --> 1
.
.
.
testthread --> 99
thread killed
testfunction--> 1
thread killed
'
'
'
testfunction--> 98
thread killed
testfunction--> 99
>>>
i expected the output like..
>>>
testthread --> 0
testfunction --> 0
testthread --> 1
testfunction --> 1
'
'
'
testthread -->99
threadkilled
testfunctionn -->99
CodePudding user response:
For one, you start out with stop_threads
being True, so the main function just cuts it out after a single iteration, then waiting for the thread you started to complete.
That's not looking at the same global, you can't just have multiple threads look at the same global and expect it to be thread-safe. However, if you simplify your code, it becomes clear that's not at all needed:
import threading
from time import sleep
def testthread():
k = 0
while k < 3:
print("testthread -->", k)
k = 1
sleep(1)
def testfunction():
t1 = threading.Thread(target=testthread)
t1.start()
i = 0
while i < 5:
print("testfunction-->", i)
i = 1
sleep(1)
t1.join()
testfunction()
Output:
testthread --> 0
testfunction--> 0
testfunction--> 1
testthread --> 1
testfunction--> 2
testthread --> 2
testfunction--> 3
testfunction--> 4
The threads effectively yield to each other on the calls to sleep()
, so the code works as expected and if you play around with the values < 3
and < 5
, you'll see either can complete.