7

Is there a recommended way to wait on multiple inputs. For example I would like my program to be able to receive input from 3 sources:

Listen on a thread condition e.g. pthread_cond_wait()

Take data from Standard input e.g. getline()

Listen on a socket e.g. accept()

What is the best way to accomplish this? Do I need a thread for each different input source? Thanks

jalf
  • 243,077
  • 51
  • 345
  • 550
  • Yes the reason for this is probably unnecessary. I should have the main thread waiting on the condition only. An "External input" thread using select() to wait on the socket and file input. Then both child threads and the "external input" thread can stimulate the main thread using the condition. –  May 27 '09 at 16:25

4 Answers4

7

No need for separate threads waiting for accept(2) and stdin - use poll/select here. Instead of conditional variable, create a pipe between threads (you already have threads if we talk about CVs), wait on it in the same poll and write to it when the event happens.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
4

On modern Linux the best way to do this is not to use pthread_cond_wait at all. Just use eventfd instead, which will enable you to listen for multiple events using select/poll/epoll.

Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181
4

You can listen on multiple file descriptors without using multiple threads using the select(2) system call. You can use pthread_cond_timedwait to wait on a condition variable with a timeout, such that you don't wait more than a particular amount of time.

I think it's highly unusual to want to simultaneously wait on either a condition variable or a file descriptor of some sort -- if you're absolutely sure that that's what you want to do, you'll have to use multiple threads, with one thread calling either pthread_cond_wait/pthread_cond_timedwait, and the other thread calling select or some other I/O function.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 11
    It's just unusual because you can't do do this (easily) on unixes. It's a very common in win32, where waiting on multiple things(socket handles, thread queues, semaphores, whatnot) is a no-brainer. – nos Jul 19 '09 at 02:22
0

It certainly seems as though these three different messaging options are mutually exclusive for a single thread; how can a single thread read from stdin while it's waiting for a thread condition?

If you really don't want to spawn three threads, the only option I can fathom is somehow modifying or parameterizing the thread, stream, and socket libraries to take a reference to a synchronization object.

veefu
  • 2,820
  • 1
  • 19
  • 29