简体   繁体   English

为什么互斥锁没有锁定变量

[英]why mutex didn't lock the variable

#define N 20
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *thread_main(void* arg){
    pthread_mutex_lock(&lock);  
    long * i = (long*)arg;
    printf("%ld\n", *i);
    pthread_mutex_unlock(&lock);
    return NULL;
}

int main()
{
    pthread_t tid[N];
    int rc;
    
    for (long i = 0; i < N; i++) {
        rc = pthread_create(&tid[i], NULL, thread_main, &i);
        if (rc) {
            fprintf(stderr, "ERROR: could not create thread\n");
            return -1;
        }
    }
    
---thread join---

}

in this code my out put is在这段代码中,我的输出是

7 7 7 7 7 7 8 9 10 10 6 12 13 14 20 20 20 20 20 20 7 7 7 7 7 7 8 9 10 10 6 12 13 14 20 20 20 20 20 20

not sure why it didn't lock long i and print it as:不知道为什么它没有长时间锁定并将其打印为:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

what's the problem and that is the strategy to solve this condition有什么问题,这是解决这种情况的策略

The variable is modified by the for loop, but that thread does not hold the mutex.该变量由for循环修改,但该线程不保存互斥锁。 The mutex didn't lock the variable because you modified the variable without holding the lock.互斥锁没有锁定变量,因为您修改了变量而没有持有锁定。

You're doing the mutex around the print function.您正在围绕打印 function 执行互斥锁。

This means that only one thing will print at once, but that's not really helpful.这意味着一次只能打印一件事,但这并没有真正的帮助。 The value of i can still change because i++ is outside the mutex. i的值仍然可以更改,因为i++在互斥锁之外。

You probably the changes to i to happen inside the mutex.您可能对i的更改发生在互斥体内部。

I suspect this is what you want:我怀疑这是你想要的:

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

#define N 20
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *thread_main(void* arg){
    pthread_mutex_lock(&lock);  
    long *i = (long*)arg;
    // Modifications to i happen inside the mutex
    printf("%ld\n", (*i)++);
    pthread_mutex_unlock(&lock);
    return NULL;
}

int main()
{
    pthread_t tid[N];
    int rc;
    long i = 0;
    
    // For/while loop does not modify value of i directly
    while (i < N) {
        rc = pthread_create(&tid[i], NULL, thread_main, &i);
        if (rc) {
            fprintf(stderr, "ERROR: could not create thread\n");
            return -1;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM