我今天写了一个pthread代码:
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *thread1(void *arg)
{
while (1) {
pthread_mutex_lock(&mutex);
sleep(1);
printf("thread1...\n");
pthread_mutex_unlock(&mutex);
}
}
void *thread2(void *arg)
{
while (1) {
pthread_mutex_lock(&mutex);
sleep(1);
printf("thread2...\n");
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, thread1, NULL);
pthread_create(&tid2, NULL, thread2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
我希望它会像这样运行:
thread1...
thread2...
thread1...
thread2...
但实际上它运行:
thread1...
thread1...
thread1...
thread1...
thread2 似乎没有运行。因此,我运行此代码超过一小时,thread2 只打印一行。他们为什么不交错运行?
我的环境:
- Ubuntu 10.04 x86_64
- Linux ubuntu 2.6.32-36-generic #79-Ubuntu SMP Tue Nov 8 22:29:53 UTC 2011 x86_64 GNU/Linux
- CPU:Intel Core i7 930(4核8线程)
谢谢你。