Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi threaded program: waiting on input

We are creating a peer to peer program (in c), and we are using multiple threads so that the program can listen for new connections and receive/send data as well.

The problem is, I remember my prof telling us that if you have multiple threads running on the same process, if one has to wait for user input, the entire process is "halted" so none of the other threads will keep running.

But then we have been reading up, and it seems like if one thread is waiting on input, the others keep running as usual...

Which one is right? If we have the program waiting for user input (ya know, things like connect to X or send X a message) on one thread, and another thread just sitting there in an infinite loop waiting for a peer to try to connect, will it still be listening for connections?

thanks! hopefully this makes sense...threads are just so confusing :(

like image 484
Toadums Avatar asked Sep 23 '26 04:09

Toadums


1 Answers

Yes, on majority of contemporary operating systems multiple threads within one process can be waiting for input (from stdin, from sockets, etc.) while other can be working.

Consider your browser. While you surf the Internet the user interface does not freeze when you wait for a page to load (i.e. one of browser's threads is waiting for the input from a socket connected to a remote host).

(...) and another thread just sitting there in an infinite loop waiting for a peer to try to connect (...)

That's called busy waiting and it's considered a bad practice. Take a look at select(2), epoll(4) or related mechanisms instead.

like image 140
Jan Avatar answered Sep 24 '26 22:09

Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!