[pthread] 同步机制(5) ---- spin lock (REALTIME)
2010-01-08 22:34:32| 分类:
pthread
| 标签:
|举报
|字号大中小 订阅
最后一个同步机制,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
------------------------------------
评论这张
转发至微博
转发至微博
评论