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/36378713/

相关文章:

c++ - g++ 编译器 : error invalid conversion from 'pthread_t {aka long unsigned int}' to 'void* (*)(void*)' [-fpermissive]

c - 什么是 char * const *?

c - 仅使用 while 和 if 对数组进行排序

c - 从文件读取到数组 - C

Python Multiprocessing : Pool. map() 似乎根本不调用函数

我可以多次运行同一个线程吗?

Java:如何启动一些异步操作并从其他线程更新用户界面?

用 C 语言实现 FIR 滤波器的循环缓冲区

c++ - 尝试使用 pthreads 访问共享数据数组时出现错误,无法访问内存地址

c - pthread_join 参数类型错误