Python Python Forking: Why Wait for User Input?

  • Thread starter Thread starter daniel_i_l
  • Start date Start date
  • Tags Tags
    Python
Click For Summary
When forking a process or starting a thread in Python, output behavior can differ based on how print statements are structured. Specifically, when using a trailing comma in a print statement, the output is buffered and does not appear on the screen until a newline character is printed. This leads to a situation where the forked process does not display its output immediately if the original program is waiting for user input. In contrast, using a print statement without a comma flushes the output immediately, allowing it to be displayed right away. This behavior is reminiscent of mutex situations where multiple threads or processes access shared resources, requiring synchronization to prevent corruption. The console's handling of output buffering and process synchronization plays a crucial role in this phenomenon.
daniel_i_l
Gold Member
Messages
864
Reaction score
0
For some reasons, if I fork a process (or start a thread) in python and let the original program wait for user input, the the forked process doesn't print anything to the screen until the newline character is printed. For example (i used '----' instead of indent):
...
ret = os.fork()
if ret == 0:
----print 'test',
else:
----data = raw_input('input: ')
doesn't print any thing to the screen. But if the 3rd line is instead
print 'test' (without comma)
then it does.
Why is this?
Thanks
 
Technology news on Phys.org
I'm no expert in this, but this reminds me of mutex situation.

Often in programs, different threads or processes use the same memory, so in order to avoid corruption, when a piece of code accesses this memory, it locks it to other code until its done.

This sounds exactly to be the case with your console you are running your code on. Threads and processes need to wait their turn, but I could be wrong, but to me this most likely seems to be the case.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 18 ·
Replies
18
Views
2K
Replies
17
Views
10K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K