CuriousKernelHacker
CuriousKernelHacker

Reputation: 100

Select behavior

It could probably be a simple question but I couldn't find a clear answer for it. I have multiple threads in c code and one of them uses select to wait for n seconds. The question that I have is that does it blocks the entire process for n seconds (like usleep) or does select blocks only the calling thread (more like nanosleep). Thanks for the answers.

Upvotes: 1

Views: 417

Answers (3)

Duck
Duck

Reputation: 27572

Yes. A sloppy but still pretty conclusive test.

#include <iostream>
#include <pthread.h>
#include <sys/time.h>

using namespace std;

pthread_mutex_t cout_mutex = PTHREAD_MUTEX_INITIALIZER;

void *task1(void *X)
{
   timeval t = {0, 100000};

    for (int i = 0; i < 10; ++i)
    {
        pthread_mutex_lock(&cout_mutex);
        cout << "Thread A going to sleep" << endl;
        pthread_mutex_unlock(&cout_mutex);

        select(0, NULL, NULL, NULL, &t);

        pthread_mutex_lock(&cout_mutex);
        cout << "Thread A awake" << endl;
        pthread_mutex_unlock(&cout_mutex);
    }

   return (NULL);
}


void *task2(void *X)
{
   pthread_mutex_lock(&cout_mutex);
   cout << "Thread B down for the long sleep" << endl;
   pthread_mutex_unlock(&cout_mutex);

   timeval t = {5, 0};
   select(0, NULL, NULL, NULL, &t);

   pthread_mutex_lock(&cout_mutex);
   cout << "Thread B glad to be awake" << endl;
   pthread_mutex_unlock(&cout_mutex);

   return (NULL);
}


int main(int argc, char *argv[])
{
  pthread_t ThreadA,ThreadB;

  pthread_create(&ThreadA,NULL,task1,NULL);
  pthread_create(&ThreadB,NULL,task2,NULL);

  pthread_join(ThreadA,NULL);
  pthread_join(ThreadB,NULL);

  return (0);
}  

Upvotes: 1

bstpierre
bstpierre

Reputation: 31226

The POSIX spec for select specifically mentions "thread" in only one place, where it talks about restoring the signal mask of the calling thread by pselect().

As with the other answers, my experience also says the answer is yes, it only blocks the calling thread.

Upvotes: 1

adamk
adamk

Reputation: 46824

I've seen several implementations in which one thread is blocking on select while other threads continue processing - so, yes, it only blocks the running thread.

(Sorry for not bringing any references)

Upvotes: 4

Related Questions