我今天写了一个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只是打印一行。 为什么他们不交错?
我的环境:
谢谢。
将睡眠移到互斥锁的外部,以便操作系统进程调度算法被释放以查看另一个线程。 问题是当你睡觉的时候,另一个线程可以被调度,但是锁定被设置,所以它不会。 当线程1唤醒时,释放锁定,然后向右循环设置。 线程2几乎没有机会进入。它正在饿死。