Chinaunix首页 | 论坛 | 博客
  • 博客访问: 49424
  • 博文数量: 23
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-05 15:34
个人简介

linux c++开发

文章分类

全部博文(23)

文章存档

2013年(23)

我的朋友

分类: LINUX

2013-12-05 15:46:16

原文地址:linux下线程锁的应用 作者:playmud

闲极无聊,为了浇灌已经荒芜的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和不加编译执行,就能看出锁的重要性了。
阅读(1078) | 评论(0) | 转发(0) |
0

上一篇:linux内核裁减

下一篇:没有了

给主人留下些什么吧!~~