LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 921|回复: 1

线程锁为什么没有起作用?

[复制链接]
发表于 2006-2-17 20:27:00 | 显示全部楼层 |阅读模式
[php]
#include<pthread.h>

int total;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *
count ()
{
  int i;
  for (i = 0; i < 100; i++)
    {
      pthread_mutex_lock (&lock);
      total++;
      pthread_mutex_unlock (&lock);
    }
}

main ()
{
  pthread_t t1, t2;
  total = 0;
  pthread_create (&t1, NULL, count, NULL);
  pthread_create (&t2, NULL, count, NULL);
  pthread_join (t1, NULL);
  pthread_join (t1, NULL);
  printf ("total=%d\n", total);
}
[/php]
发表于 2006-2-17 21:50:37 | 显示全部楼层
不是线程的问题,阻塞条件的问题。
pthread_join (t1, NULL);
pthread_join (t1, NULL);
改成
pthread_join (t1, NULL);
pthread_join (t2, NULL);
就好了。
如果不这样,结果是不一定的。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表