2

If I spawn two threads that use the same libc socket, one for read and one for write, will there be a problem?

Derek Chiang
  • 3,330
  • 6
  • 27
  • 34
  • can you put in your question in which platform are you working on? – Netorica Jan 08 '14 at 15:37
  • Reads and writes use two independent buffers - they don't share anything (possibly it depends on a platform, but I doubt it). In this case I doubt there will be a problem, no matter what socket lib you use. I might be wrong though - looking forward to other comments. – freakish Jan 08 '14 at 15:44
  • 1
    A similar question exists [**about parallel calls to send/recv**](http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid) – Mark Wilkins Jan 08 '14 at 16:07
  • There won't be a direct problem -- the read() and write() calls won't interfere with each other -- but you may find it tricky to shut down your program reliably. You won't want to close() your socket until both threads have stopped using it, of course, which generally means telling both threads to exit and then calling join() on both of them. But how do you tell the read-thread to exit when it is blocked (possibly forever) in a recv() call? Signals are out since they don't play well with threads. In my experience it's easier to use just one thread and multiplex I/O with select() or poll(). – Jeremy Friesner Feb 03 '14 at 05:48

1 Answers1

1

In Unix systems, a socket is just an integer in userspace, the actual socket is inside the kernel. You could even have two different processes manipulating the same socket (one reading, other writing) with no problem.

epx
  • 1,066
  • 9
  • 17