linux - 为什么我的两个线程不交错运行?

标签 linux multithreading pthreads multicore

我今天写了一个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 11 月 8 日星期二 22:29:53 UTC 2011 x86_64 GNU/Linux
  • CPU:Intel Core i7 930(4 核、8 线程)

谢谢。

最佳答案

将 sleep 移出互斥锁,以便操作系统进程调度算法可以释放以查看其他线程。问题是,当您 sleep 时,另一个线程可以得到调度,但锁已设置,所以它不会。当线程 1 唤醒时,它会释放锁,但随后又循环回来设置锁。线程 2 几乎没有机会进入。它正在挨饿。

关于linux - 为什么我的两个线程不交错运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14160418/

相关文章:

linux shell脚本数学运算

编译的C文件不可执行

c# - 锁定字段或局部变量?

c++ - Pthread 条件变量不可预测的结果

linux - Linux 信号在内核内部的什么地方发送或处理?

c - Linux 上的 pthread 执行

python - 在Python中,创建一个线程然后join()比正常的阻塞过程有什么好处吗?

c++ - 线程池的 lambda 函数内部的编译器错误变量 "Not captured"

c - 试图理解c中的死锁

在返回 Go Runtime 之前,Cgo 在 x_cgo_notify_runtime_init_done 中被阻塞