加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

没法贴图,发个博客吧,关于lock

(2012-06-30 12:12:10)
标签:

杂谈

关于微博上提到的,pthread mutex的等待排队的实验。

我理解的这个mutex是直接被阻在队列中,由释放者来进行调度,所以是非常重量级的,如果资源短暂开闭,则应用spinlock为佳,例如对一块内存的某个字节进行外科手术打击,则spinlock快进快出好。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include<iostream>
using namespace std;

static pthread_mutex_t foo_mutex;

void* get_maokeng(void* param)
{
        fprintf(stderr,"i like to paifang shit! %d\n",*(int*)param);
        pthread_mutex_lock(&foo_mutex);
        fprintf(stderr,"i first get maokeng! haha! %d\n",*(int*)param);
}

void* go_maokeng(void* param)
{
        fprintf(stderr,"i like to paifang shit! %d\n",*(int*)param);
        pthread_mutex_lock(&foo_mutex);
        fprintf(stderr,"i get maokeng! %d\n",*(int*)param);
        pthread_mutex_unlock(&foo_mutex);
};

int main()
{
        pthread_mutex_init(&foo_mutex, NULL);

        pthread_t* thread = (pthread_t*) malloc( 10 *sizeof( pthread_t));
        int token[10]={0,1,2,3,4,5,6,7,8,9};

        pthread_create(&thread[0],NULL,get_maokeng,&token[0]);
        sleep(1);
        for(int i=1;i<10;++i)
        {
                pthread_create(&thread[i],NULL,go_maokeng,&token[i]);
                sleep(1);
        }
        pthread_mutex_unlock(&foo_mutex);

        for(int i=0;i<10;++i)
        {
                pthread_join(thread[i],NULL);
        }
        free(thread);
        return 0;
}

运行结果:【排队的效果很明显】
i like to paifang shit! 0
i first get maokeng! haha! 0
i like to paifang shit! 1
i like to paifang shit! 2
i like to paifang shit! 3
i like to paifang shit! 4
i like to paifang shit! 5
i like to paifang shit! 6
i like to paifang shit! 7
i like to paifang shit! 8
i like to paifang shit! 9
i get maokeng! 1
i get maokeng! 2
i get maokeng! 3
i get maokeng! 4
i get maokeng! 5
i get maokeng! 6
i get maokeng! 7
i get maokeng! 8
i get maokeng! 9

0

阅读 收藏 喜欢 打印举报/Report
前一篇:感触
后一篇:江湖
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有