登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Code@Pig Home

喜欢背着一袋Code傻笑的Pig .. 忧美.欢笑.记忆.忘却 .之. 角落

 
 
 

日志

 
 

[pthread] 同步机制(5) ---- spin lock (REALTIME)  

2010-01-08 22:34:32|  分类: pthread |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
最后一个同步机制,spinlock (自旋锁)。spinlock 用法与 mutex 类似,但 spinlock 在 block 时是 busy wait。
这可通过 top 明显看到。

------------------------------------
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>

pthread_spinlock_t global_sl;

void *mythr(void *arg)
{
    int n = (int)arg;
    pthread_spin_lock(&global_sl);
    printf("thr #%d lock, time = %d\n", n, time(NULL));
    sleep(2);
    pthread_spin_unlock(&global_sl);
    return (void *)0;
}

int main()
{
    pthread_t pid1, pid2;
    pthread_spin_init(&global_sl, PTHREAD_PROCESS_PRIVATE);

    pthread_create(&pid1, NULL, mythr, (void *)1);
    pthread_create(&pid2, NULL, mythr, (void *)2);
   
    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);

    pthread_spin_destroy(&global_sl);
    return 0;
}
------------------------------------
$ ./a.out
thr #1 lock, time = 1262961184
thr #2 lock, time = 1262961186
------------------------------------
  评论这张
 
阅读(1811)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018