- 论坛徽章:
- 0
|
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
void*
thread(void *arg)
{
while(1) {
pthread_mutex_lock(&mutex);
printf("pthread:%d\n", (int)arg);
sleep(2);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int
main(void)
{
int i;
pthread_t pid[10];
pthread_mutex_init(&mutex, NULL);
for (i = 0; i < 10; i++) {
pthread_create( pid + i, NULL, thread, (void*)i);
}
while(1)
;
return 0;
}
输出:
pthread:0
pthread:0
pthread:0
pthread:0
pthread:0
pthread:0
pthread:0
pthread:0
pthread:0
.
.
.
为什么不是这样:
pthread:0
pthread:1
pthread:2
pthread:3
pthread:4
pthread:5
pthread:6
pthread:7
pthread:8
是不是因为系统调度的时候不考虑互斥锁,也就是互斥锁没有等待队列
只要线程在运行,并且没有其他线程正在占用互斥锁,就可以得到锁,不考虑互斥的先后
有没有介绍多线程锁方面的资料,谢谢共享一下 |
|