linux多線程的互斥鎖問題

1、原因

寫這篇記錄一下的原因是,有個項目(NPU)存在一點問題,而且是那種比較讓人頭疼麻煩崩潰的問題,人臉數據一開始傳的好好地,隔三差五就會沒數據,重啓程序後又回覆(他們說是這樣,我自己倒是還沒見過沒數據推上來的時候)

2、多線程中的互斥鎖

這是在源程序中看到的一個可疑的地方,簡單來說就是,在將任務壓到隊列中的時候,需要去獲取相應的鎖(防止數據出現時間上的問題)但是問題是,該鎖的初始化步驟還沒有進行到,但是執行過程卻是沒啥問題,對互斥量加鎖(pthread_mutex_lock)或者解鎖(pthread_mutex_unlock)的時候互斥量卻還沒有進行初始化,就是還沒有pthread_mutex_init,這從嚴謹方面看絕對是有問題的,不過若是初始化的操作和定義時的賦值操作是一樣的(比如說都給的是0)那按道理初不初始化又似乎沒有影響,自己於是寫了個測試程序,結果臥槽看起來還真的是沒有影響。但是又有網上大神說了"互斥鎖對象必須通過其API初始化,不能使用memset或者複製初始化"這就讓我頭大了…

3、測試代碼

/*程序讓子線程打印小寫,主控線程打印大寫,用sleep模擬CPU易主*/
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

pthread_mutex_t mutex;      //定義鎖

void *tfn(void *arg)
{
    srand(time(NULL));

    while (1) {
        pthread_mutex_lock(&mutex);

        printf("hello ");
        sleep(rand() % 3);	/*模擬長時間操作共享資源,導致cpu易主,產生與時間有關的錯誤*/
        printf("world\n");
        pthread_mutex_lock(&mutex);

        sleep(rand() % 3);
    }

    return NULL;
}

int main(void)
{
    int flg = 5;
    pthread_t tid;
    srand(time(NULL));

    pthread_mutex_init(&mutex, NULL);  // 就是這個地方,若是註釋了,結果似乎沒有啥影響......
    pthread_create(&tid, NULL, tfn, NULL);
    while (flg--) {

        pthread_mutex_lock(&mutex);

        printf("HELLO ");
        sleep(rand() % 3);
        printf("WORLD\n");
        pthread_mutex_unlock(&mutex);

        sleep(rand() % 3);

    }
    pthread_cancel(tid);
    pthread_join(tid, NULL);

    pthread_mutex_destroy(&mutex);  

    return 0;
}

不去註釋,一切嚴謹結果:
HELLO WORLD
hello world
HELLO WORLD
hello world
HELLO WORLD
HELLO WORLD
hello world
hello world
HELLO WORLD
hello world
hello world
hello world
HELLO WORLD
hello world
hello world
HELLO WORLD
hello world
HELLO WORLD
hello world
hello world
HELLO WORLD

將初始化API註釋了:
HELLO WORLD
HELLO WORLD
HELLO WORLD
hello world
HELLO WORLD
HELLO WORLD
hello world
HELLO WORLD
hello world
HELLO WORLD
HELLO WORLD
HELLO WORLD
hello world
hello world
HELLO WORLD
HELLO WORLD
hello world
HELLO WORLD
hello world
HELLO WORLD
hello world
hello world
hello world
HELLO WORLD
HELLO WORLD

結果反正我肉眼看上去看不出什麼差別…
這個初始化的函數設計絕對不可能是可有可無的,不過到現在還是不知道不去初始化會造成什麼問題,求懂得人給個說法啊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章