简体   繁体   中英

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

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

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. 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.

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.

You probably the changes to i to happen inside the mutex.

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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