c - Is read/recv thread safe (MSG_PEEK) -
i have 1 thread doing blocking read
:
rec = read(socket, data, size);
i'm curious know whether safe or not me have thread, doing recv(msg_peek)
in background on same socket:
while (true) { if (recv(socket, byte, size, msg_dontwait | msg_peek) > 0) { printf("peeked %d", byte); } sleep(1); }
since syscalls operate in kernel space, thread safe (they have be, otherwise kernel data corrupted , bring down entire system) in sense program won't crash - however, noted jeremy friesner in comments:
the order in syscalls executed may not guaranteed.
syscalls take time. means lot of data slip past in between calls
recv ()
.
however, write bytes named fifo. open writing end in thread doing read ()
, reading end in thread doing recv ()
.
now, every time complete read ()
, write first byte (that's wanted, yeah?) fifo. meanwhile, in other thread, instead of using sleep ()
in between recv ()
, use blocking read
of size 1 byte on fifo , printf ()
result.
this way, kernel can automatically wake recv ()
thread whenever there data read. don't waste cpu time unnecessary context switches either (which pretty big), application's overall performance/speed go too.
Comments
Post a Comment