EDIT : Actually what happened was that I ran it in Programmer's Notepad and it waited for the program to complete before capturing the stdout output and printing it to console, then I ran it from mingw which worked as expected. This behavior is obvious and expected, I just haven't realized that I was running the program in programmer's notepad rather than shell as I usually do. My bad.
I was playing with Python threads, but ran into this weird problem where if I have a print statement and a 1 second sleep statement inside the callback function, it doesn't do the printing until the sum of the sleep times has elapsed.
here is the code that causes this behavior:
import threading
import time
def callback():
for i in range(3):
print "Hello, World!";
time.sleep(1)
myThread = threading.Thread (
target = callback,
args = []
)
myThread.start()
This is how I want it to behave:
public class Demo
{
public static void main(String[] args)
{
(new Thread(() -> {
for (int i = 0; i < 3; ++i) {
System.out.println("Hello, World!");
try {
Thread.sleep(1000);
} catch(Exception e){
// rethrow as an unchecked exception but do not silence it.
throw (RuntimeException)e;
}
}
})).start();
}
}
What is causing Python to behave this way, and how can I get it to behave the way I expect it to?
Based on your comments, I have a feeling that your problem is due to the system not flushing stdout. To fix it, try this:
import sys
Then right after your print function:
sys.stdout.flush()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.