当前位置: 技术问答>linux和unix
linux 多线程锁的问题 trylock得不到锁
来源: 互联网 发布时间:2017-04-04
本文导语: 如题: 测试代码如下,为何线程一中while的最后不sleep 1s,那么线程2trylock就永远的得不到锁,这个正常吗? #include #include pthread_mutex_t mutex; pthread_cond_t cond; int sum = 0; void *thread1(void *arg) { while(1) ...
如题:
测试代码如下,为何线程一中while的最后不sleep 1s,那么线程2trylock就永远的得不到锁,这个正常吗?
测试代码如下,为何线程一中while的最后不sleep 1s,那么线程2trylock就永远的得不到锁,这个正常吗?
#include
#include
pthread_mutex_t mutex;
pthread_cond_t cond;
int sum = 0;
void *thread1(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
sum++;
printf("thread1--->%dn",sum);
sleep(3);
pthread_mutex_unlock(&mutex);
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
sleep(1); /*只有开启睡眠才可以让trylock获得锁*/
}
}
void *thread2(void *arg)
{
printf("start thread2....n");
while(1)
{
int rel = pthread_mutex_trylock(&mutex);
if(0 == rel)
{
sum--;
printf("thread2-->%dn",sum);
pthread_mutex_unlock(&mutex);
}
}
}
int main()
{
printf("testn");
sleep(1);
pthread_t thid1, thid2;
printf("condition variable study!n");
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&thid1, NULL, (void *) thread1, NULL);
pthread_create(&thid2, NULL, (void *) thread2, NULL);
pthread_join(thid1,NULL);
pthread_join(thid2,NULL);
return 0;
}
|
没有sleep(1)的话
pthread_mutex_unlock 之后 立即调用 pthread_mutex_lock,
建议thread1里pthread_mutex_unlock之后sched_yield
thread2里pthread_mutex_trylock 改为pthread_mutex_lock
pthread_mutex_unlock 之后 立即调用 pthread_mutex_lock,
建议thread1里pthread_mutex_unlock之后sched_yield
thread2里pthread_mutex_trylock 改为pthread_mutex_lock
|
把 printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
sleep(1); /*只有开启睡眠才可以让trylock获得锁*/
这几句都去掉也没问题!
./a.out | head -20
test
condition variable study!
start thread2....
thread1--->1
thread2-->0
thread2-->-1
thread2-->-2
thread2-->-3
thread2-->-4
thread2-->-5
thread2-->-6
thread2-->-7
thread2-->-8
thread2-->-9
thread2-->-10
thread2-->-11
thread2-->-12
thread2-->-13
thread2-->-14
thread2-->-15
当然可能会出现线程1在一个时间片内刚好循环一遍,,那当线程2获得时间片时,线程2就每次都获得不到锁了. 这种情况应该只会发生在单核cpu上吧.
我的是双核的cpu.
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
printf("thread1--->n");
sleep(1); /*只有开启睡眠才可以让trylock获得锁*/
这几句都去掉也没问题!
./a.out | head -20
test
condition variable study!
start thread2....
thread1--->1
thread2-->0
thread2-->-1
thread2-->-2
thread2-->-3
thread2-->-4
thread2-->-5
thread2-->-6
thread2-->-7
thread2-->-8
thread2-->-9
thread2-->-10
thread2-->-11
thread2-->-12
thread2-->-13
thread2-->-14
thread2-->-15
当然可能会出现线程1在一个时间片内刚好循环一遍,,那当线程2获得时间片时,线程2就每次都获得不到锁了. 这种情况应该只会发生在单核cpu上吧.
我的是双核的cpu.