Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use one socket in two threads [duplicate]

Tags:

c++

c

sockets

Possible Duplicate:
Are parallel calls to send/recv on the same socket valid?

I'm going to use one thread to receive data from socket(read) and another one to send data throughout socket(write).

Is it good idea to use one socket in two different threads?

like image 794
Dejwi Avatar asked Sep 14 '11 14:09

Dejwi


1 Answers

There should be no problems sharing a socket across threads. If there is any kind of coordination required between the reading and the writing, and there probably will be, you're going to need to synchronize that in some way.

This article, File Descriptors And Multithreaded Programs, may be helpful and addresses the comment below.

... the socket library used for this should be threadsafe to start with and support a read from a socket in one thread and a write to the socket in the other ... The raw system calls read() and write() support this

From the socket manpage

Sockets of type SOCK_STREAM are full-duplex byte streams

You should be able to read and write both directions no problem, the directions are just about unrelated once the connection has been set up, at least in TCP.

like image 173
Paul Rubel Avatar answered Oct 14 '22 11:10

Paul Rubel