日期:2014-05-16  浏览次数:20830 次

多个线程同时等待一个锁,获取锁的机制是什么??
多个线程同时等待一个锁,当锁可用时,哪个能首先获取??是按等待锁的时间还是线程的优先级??
以下三个线程优先级一样,等待时间不一样。
结果是:bst1
bst2
bst3
bst1
bst1
bst1
bst1
bst1
bst3
bst3
bst3
bst3
bst3
bst2
bst2
bst2
bst2
bst2
感觉不太对啊??


void   *thread1(void   *arg)
{
int   i;
struct   timeval   tv;
i=0;
tv.tv_sec=0;
tv.tv_usec=500;
while(i <6)
{
pthread_mutex_lock(&bst_mutex);
printf( "bst1\n ");
pthread_mutex_unlock(&bst_mutex);
select(0,NULL,NULL,NULL,&tv);
i++;
}
}
void   *thread2(void   *arg)
{
int   i;
struct   timeval   tv;
i=0;
tv.tv_sec=0;
tv.tv_usec=1000;
while(i <6)
{
pthread_mutex_lock(&bst_mutex);
printf( "bst2\n ");
pthread_mutex_unlock(&bst_mutex);
select(0,NULL,NULL,NULL,&tv);
i++;
}
}
void   *thread3(void   *arg)
{
int   i;
struct   timeval   tv;
i=0;
tv.tv_sec=0;
tv.tv_usec=800;

while(i <6)
{
pthread_mutex_lock(&bst_mutex);
printf( "bst3\n ");
pthread_mutex_unlock(&bst_mutex);
select(0,NULL,NULL,NULL,&tv);
i++;
}
}

int   main(void)
{
struct   timeval   tv;

pthread_mutex_lock(&bst_mutex);
ret=pthread_create(&SetParaId,NULL,(void   *)thread1,NULL);
if(ret!=0)
{
          exit   (1);
}
ret=pthread_create(&BSendId,NULL,(void   *)thread2,NULL);
if(ret!=0)
{
          exit   (1);
}
ret=pthread_create(&VSleepId,NULL,(void   *)thread3,NULL);
if(ret!=0)
{
                            exit   (1);
}
tv.tv_sec=2;
tv.tv_usec=0;
select(0,NULL,NULL,NULL,&tv);
pthread_mutex_unlock(&bst_mutex);
pthread_join(BSendId,NULL);
pthread_join(VSleepId,NULL);
pthread_join(SetParaId,NULL);
return   1;

------解决方案--------------------
线程调度,我觉得是不可预测的。线程优先级会动态调整的。
你多运行几次比较一下。
------解决方案--------------------
队列不是先进先出的,一旦锁可用,所有线程醒过来,获得调度机会运行的线程获得锁,其他继续睡眠
------解决方案--------------------
不知这个和windows 里的同步是不是一样的
在windows里是多个线程等特一个内核资源,这些线程是平等调度的