Pthread互斥不能正常工作 [英] pthread mutex not working correctly

查看:98
本文介绍了Pthread互斥不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在学习从麻省理工学院的开放式课件过程称为C.实际编程在多线程讨论竞争条件C,讲义包含一个具有竞争条件的程序的例子,它如何使用互斥量来解决。在code按预期运行在Linux系统上,而不是在OS X。

I am currently learning C from MIT's Open Courseware course called Practical Programming in C. In discussing race conditions in multithreading, the lecture notes contained an example of a program with a race condition and how it could be resolved using a mutex. The code works as expected on linux systems, but not on 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的理想正确的响应(4亿),在每次运行时不同的变量部分。加入互斥之后,这还是发生,虽然有在结果明显增加,这表明它有部分的预期效果,但远非完美。

Before adding the mutex and the corresponding function calls, the behavior was as expected, producing a variable fraction of the ideally correct response for cnt (400000000), different on each run. After adding the mutex, this was still happening, although there was an obvious increase in the results, suggesting it had some of the expected effect, but far from perfect.

我试过其他3台电脑/ VMS编译此程序:一个正在运行的OS X 10.10(第一次是跑10.11),一个与Linux的卡利(引擎盖下基本上是Debian的杰西),和一个运行Ubuntu。无论是OS X上运行的表现描述的一样奇怪的行为。然而,在Linux系统产生的4亿的完美预期。

I tried compiling this program on 3 other computers/VMs: one running OS X 10.10 (the first was running 10.11), one with Kali Linux (essentially Debian Jessie under the hood), and one running Ubuntu. Both of the OS X runs showed the same odd behavior as described. However, both Linux systems produced the perfect 400000000 as expected.

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

So my question is, why doesn't the mutex work as expected on OS X?

推荐答案

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

You didn't initialize the mutex. You can either do this:

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

功能,做到这一点:

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

这篇关于Pthread互斥不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆