Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15485109
  • 博文数量: 112
  • 博客积分: 11195
  • 博客等级: 上将
  • 技术积分: 1989
  • 用 户 组: 普通用户
  • 注册时间: 2005-06-20 11:04
文章分类

全部博文(112)

文章存档

2013年(2)

2012年(27)

2011年(6)

2010年(11)

2009年(6)

2007年(7)

2006年(23)

2005年(30)

分类: LINUX

2006-12-27 02:08:13

闲极无聊,为了浇灌已经荒芜的BLOG,胡乱写写代码。
 

/**********************************************
作者:猪头流氓
时间:Tue Dec 26 16:45:30 2006
文件名:tt.c
描述:

gcc -o target tt.c -lpthread

gcc -o target tt.c -lpthread -DLOCK
**********************************************/
#include
#include

#ifdef LOCK
pthread_mutex_t lm;
#endif

void * func(void * avg);
int count;
int main()
{

#ifdef LOCK
        pthread_mutex_init(&lm, NULL);
#endif
        pthread_t pa,pb;
        pthread_create(&pa, NULL, &func, NULL);
        pthread_create(&pb, NULL, &func, NULL);
        pthread_join(pa, NULL);
        pthread_join(pb, NULL);
        return 0;

}

void * func(void *avg)
{
        int i, val;
        for(i=0; i<20; i++) {
#ifdef LOCK
                pthread_mutex_lock(&lm);
#endif
                val=count;
                int rd=random();
                sleep(rd%2);
                printf("%u:%d\n", pthread_self(), val+1);
                count++;
#ifdef LOCK
                pthread_mutex_unlock(&lm);
#endif
        }

}
 

分别按照加-DLOCK和不加编译执行,就能看出锁的重要性了。
阅读(106626) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~