multithreading - Mutexs with pipes in C -
i sorry if sounds repeating question, have couple additions hoping can explain me.
i trying implement 'packet queueing system' pipes. have 1 thread has packet of data needs pass second thread (lets call threads , b respectively). did queueing structure implemented using linked lists. lock mutex, write queue, , unlock mutex. on read side, same thing, lock, read, unlock. decided change implementation , make use of pipes (so can make use of blocking when data not available). question:
do need use mutexs lock file descriptors of pipe read , write operations?
here thinking.
i have standard message gets written pipe on writes, , expected read on read side.
struct pipe_message { int stuff; short more_stuff; char * data; int length; }; // read pipe num_bytes_read = read(read_descriptor, &buffer, sizeof(struct pipe_message)); if(num_bytes_read != sizeof(struct pipe_message)) // if message isn't full { printe("error: read did not receive full message\n"); return null; }
if not use mutexs, potentially read half of message pipe? bad because not have pointer data , left memory leaks.
but, if use mutexs, lock mutex on read, attempt read block, , because mutex locked, write side not able access pipe.
do need use mutexs lock file descriptors of pipe read , write operations?
it depends on circumstances. normally, no.
normality
if have single thread writing pipe's write file descriptor, no. nor reader need use semaphores or mutexes control reading pipe. that's taken care of os underneath on behalf. go ahead , call write() , read(); nothing else required.
less usual
if have multiple threads writing pipe's write file descriptor, answer maybe.
under linux calling write() on pipe's write file descriptor atomic operation provided size of data being written less amount (this specified in man page pipe(), recall it's 4kbytes). means don't need mutex or semaphore control access pipe's write file descriptor.
if size of data you're writing large then call write() on pipe not atomic. if have multiple threads writing pipe , size large need mutex control access write end of pipe.
Comments
Post a Comment