[LC++]sockets

Jack Lloyd lloyd at acm.jhu.edu
Wed Jul 3 06:55:08 UTC 2002


On Tue, 2 Jul 2002, Peter Poulsen wrote:

> I know this is really a c question, but I'm programming in c++ so hope
> it ok.

No! Bad! Well, OK, I suppose just this once. :)

> I have a couple of threads running, and i would like to know if it can
> give any problems if one thread tries to write while another is reading?

Oh, yes. I mean it depends on the application, but I can imaginge all kinds
of horribleness that could (potentially) occur.

But from a purely API standpoint, it's fine. There isn't anything wrong
(that I know of) about having one thread blocked in a read on an fd while
another thread does a write on the same fd - assuming that fd is a TCP
socket. Files are another story, you're likely to get very inconsistent
results in that case.

> As I see it I cannot but mutexs' around the socket, as the reading
> thread just sit there and wait for something to come along. If I put
> mutexs' around the socket, it would mean that all the sending threads
> would wait for something to arrive before the reading thread would
> release the lock.

You could make the socket non-blocking, I suppose. Unfortunately, dup(2)
copied flags, so you would have to make the writing sockets non-blocking as
well. You could work around _that_ by using select. All in all, it seems
excessively complicated.

> To be more specifik: I have one reading thread, and multiple writing
> threads.

Multiple threads writing to a single socket? Be careful, because you can't
really be assured that the output isn't being mixed back and forth between
various threads. Like, if one was writing "AAA" and the other wrote "BBB"
you might get AAABBB or ABABAB or ABBBAA or whatever when you do a read on
the other side of the socket. Since write is a system call you can probably
assume that writes of less than 1.5 kbytes are atomic, but it's still
pretty dangerous.

I just realized this response is probably not particularly helpful. If you
could maybe provide more details about your program, somewhat more useful
advice might follow.

Regards,
  Jack





More information about the tuxCPProgramming mailing list