当前位置: 技术问答>linux和unix
pthread 阻塞问题
来源: 互联网 发布时间:2015-09-07
本文导语: pthread 阻塞问题 #include #include #include pthread_t pid; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond=PTHREAD_COND_INITIALIZER; void thread(void) { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); pthread_mutex_unlock(&mutex...
pthread 阻塞问题
#include
#include
#include
pthread_t pid;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void thread(void)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
pthread_mutex_unlock(&mutex);
printf("This is a threadn");
}
int main()
{
pthread_t id;
int ret;
ret=pthread_create(&id,NULL,(void*)thread,NULL);
if(ret)
{
printf("create thread error");
exit(1);
}
//getchar();?????????????
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_join(id,NULL);
return 0;
}
1.为什么在main中执行了pthread_cond_signal(&cond),thread()线程仍然阻塞???而我把getchar()加上就解开pthread_cond_wait阻塞
2.其实我这么做的目的是想创建个线程就马上将它先挂起(类似windwos下的线程函数创建一个挂起的线程),是否有更好的方法?
#include
#include
#include
pthread_t pid;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void thread(void)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
pthread_mutex_unlock(&mutex);
printf("This is a threadn");
}
int main()
{
pthread_t id;
int ret;
ret=pthread_create(&id,NULL,(void*)thread,NULL);
if(ret)
{
printf("create thread error");
exit(1);
}
//getchar();?????????????
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_join(id,NULL);
return 0;
}
1.为什么在main中执行了pthread_cond_signal(&cond),thread()线程仍然阻塞???而我把getchar()加上就解开pthread_cond_wait阻塞
2.其实我这么做的目的是想创建个线程就马上将它先挂起(类似windwos下的线程函数创建一个挂起的线程),是否有更好的方法?
|
一个竞争问题,pthread_cond_signal先于pthread_cond_wait导致丢失.
只用mutex或者semaphore就可以了
只用mutex或者semaphore就可以了