0

Is it legal to accept and read from TCP socket in one thread and write data in same socket in another thread on Linux?

Example:
// thread #1
// ...
int sock = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen));
// .. read from socket sock

#thread #2
// ...
int n = send(sock, buffer, 1024);
// ...

it is legal or undefined behaviour?

Joseph Conrad
  • 43
  • 1
  • 6
  • It's fine, if a bit overkill for inter thread communication. – Shawn Jul 04 '22 at 08:10
  • Difficult to do. How does the writing thread know about the `sock`, the accepted socket? In general the accepting thread should not do any I/O with the accepted sockets, otherwise that I/O can block and hold up subsequent connect attempts. Every accepted socket should have its I/O done in a new thread. – user207421 Jul 04 '22 at 08:48
  • @Shawn what you mean under overkill? – Joseph Conrad Jul 04 '22 at 10:10
  • @user207421 There are no locks because non-blocking sockets are used. The writing thread checks the queue and then know about the accepted socket if the queue is not empty – Joseph Conrad Jul 04 '22 at 10:11
  • Compared to pipes (one way), anonymous unix domain sockets created with `socketpair()` (two way), thread safe message queues, etc... – Shawn Jul 04 '22 at 16:15

0 Answers0