0

In my problem, I create a pthread using pthread_create(), say myThread.

They both share a common variable "done" for the main thread to tell the myThread stops reading from the socket.

in my pthread, I have a loop:

// done is a common variable
while (!done && socket->read(&buffer) == OK) {
    // do something....
}

Some times, I want to tell myThread to stop reading from socket, so I do:

done = true;
  void *test;
    pthread_join(myThread, &test);

Will this cause a race condition? i.e. will myThread not see my main thread update the value of 'done' before it blocks on the read call?

michael
  • 106,540
  • 116
  • 246
  • 346

1 Answers1

0

Writing a variable in one thread and reading it in another needs synchronization (such as a mutex) to avoid race conditions.

If this is a real socket and not a strange object, consider calling shutdown() to tear down the connection and wake up blocked threads while keeping the file descriptor valid, see Wake up thread blocked on accept() call. Once the read has failed, myThread locks the mutex and checks the done variable.

Other methods include calling poll() on the socket and a pipe for delivering the shutdown message.

Community
  • 1
  • 1
jilles
  • 10,509
  • 2
  • 26
  • 39