簡體   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---

}

在這段代碼中,我的輸出是

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

不知道為什么它沒有長時間鎖定並將其打印為:

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

有什么問題,這是解決這種情況的策略

該變量由for循環修改,但該線程不保存互斥鎖。 互斥鎖沒有鎖定變量,因為您修改了變量而沒有持有鎖定。

您正在圍繞打印 function 執行互斥鎖。

這意味着一次只能打印一件事,但這並沒有真正的幫助。 i的值仍然可以更改,因為i++在互斥鎖之外。

您可能對i的更改發生在互斥體內部。

我懷疑這是你想要的:

#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