c - pthread 互斥体无法正常工作

标签 c multithreading pthreads mutex

我目前正在通过麻省理工学院的名为“C 实用编程”的开放课件类(class)学习 C。在讨论多线程中的竞争条件时,讲义包含一个具有竞争条件的程序示例以及如何使用互斥体解决该问题。该代码在 linux 系统上按预期工作,但在 OS X 上不工作。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_mutex_t mutex; // Added to fix race condition
unsigned int cnt = 0;

void *count(void *arg) {
    int i;
    for (i = 0; i < 100000000; i++) {
        pthread_mutex_lock(&mutex); // Added to fix race condition
        cnt++;
        pthread_mutex_unlock(&mutex); // Added to fix race condition
    }
    return NULL;
}

int main() {
    pthread_t tids[4];
    int i;
    for (i = 0; i < 4; i++)
        pthread_create(&tids[i], NULL, count, NULL);
    for (i = 0; i < 4; i++)
        pthread_join(tids[i], NULL);
    pthread_mutex_destroy(&mutex); // Added to fix race condition
    printf("cnt = %u\n", cnt);
    return 0;
}

在添加互斥锁和相应的函数调用之前,行为符合预期,为 cnt (400000000) 产生理想正确响应的可变部分,每次运行都不同。添加互斥锁后,这种情况仍然存在,虽然结果有明显的增加,表明它具有一些预期的效果,但远非完美。

我尝试在其他 3 台计算机/VM 上编译该程序:一台运行 OS X 10.10(第一台运行 10.11),一台运行 Kali Linux(本质上是 Debian Jessie),一台运行 Ubuntu。两个 OS X 运行都显示出与描述的相同的奇怪行为。然而,两个 Linux 系统都按预期产生了完美的 400000000。

所以我的问题是,为什么互斥量在 OS X 上不能按预期工作?

最佳答案

您没有初始化互斥锁。您可以这样做:

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

或者在 main 函数中,这样做:

if ( pthread_mutex_init( &mutex, NULL) != 0 )
    printf( "mutex init failed\n" );

关于c - pthread 互斥体无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34936019/

相关文章:

c - 在c中的新窗口中打印线程的输出

c - 使用 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP 和 -Wextra 时如何避免编译器警告

c# - 如何判断子线程是否完成

c - 数组访问,指针混淆

java - 如何在 C 中使用 Long 数据类型?

c - 有没有一种简单的方法来显示 code::blocks 中变量的地址?

python - 当我在 python 和 pyqt 中关闭应用程序时不运行类析构函数

java - 试图阻止 Swing worker

c++ - 一个简单的 pthread_create 在 Qt 中导致 100% 的 CPU 使用率

c - 在非阻塞模式下创建多个 TCP 连接时内核日志中的 net_ratelimit 消息