Search code examples
clinuxmultithreadingsocketscontext-switch

Multi threaded socket context switch in c


environment: Linux
language: C

If i have server and client processes.
server use socket to communicate with client.

At server process,it has two threads(thread 1,thread 2).
(thread 1 and thread 2 share the same file descriptor to communicate with client).
At client process,it just single thread.

I excepted
server:

thread 1:
send message A.1 to client
recv message A.2 from client

thread 2:
send message B.1 to client
recv message B.2 from client

but multi-thread it maybe happened context switch

server:

thread 1:
send message A.1 to client

context switch

thread 2: 
send message B.1 to client
recv message A.2 from client

context switch

thread 1:
recv message B.2 from client

how to avoid thread 2 recv A.2 from client??
can i prevent context switch until thread 1 recv A.2 message?


Solution

  • The easiest (bad practice, not-optimal) way is to have a mutex that blocks thread 2 to send message B.1 until A.2 has been received.

    A better (and more complicated way) would be to have one thread that receives responses and dispatched the messages to correct thread, but then you need a message loop on each thread for communication with the dispatcher.