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.
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)
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.
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);
}
精彩评论