linux - Multi threaded socket context switch in c -


environment: linux
language: c

if have server , client processes.
server use socket communicate client.

at server process,it has 2 threads(thread 1,thread 2).
(thread 1 , thread 2 share same file descriptor communicate client).
@ client process,it single thread.

i excepted
server:

thread 1: send message a.1 client recv message a.2 client  thread 2: send message b.1 client recv message b.2 client 

but multi-thread maybe happened context switch

server:

thread 1: send message a.1 client  context switch  thread 2:  send message b.1 client recv message a.2 client  context switch  thread 1: recv message b.2 client 

how avoid thread 2 recv a.2 client??
can prevent context switch until thread 1 recv a.2 message?

the easiest (bad practice, not-optimal) way have mutex blocks thread 2 send message b.1 until a.2 has been received.

a better (and more complicated way) have 1 thread receives responses , dispatched messages correct thread, need message loop on each thread communication dispatcher.


Comments