簡體   English   中英

如何使用 pthreads 從 C 中的另一個線程安全地修改字符串?

[英]How to safely modify string from another thread in C with pthreads?

我正在嘗試在 C 中創建一個簡單的 CLI 音樂播放器。 除了負責播放音樂的主線程之外,我還創建了第二個線程。 第二個線程接收這樣的參數(我嘗試過使用和不使用 volatile 關鍵字):

typedef struct AUDIO_S
{
    volatile char audio_path[MAX_PATH];
    volatile int play_state;
} audio_t;

主線程可能會更新音頻路徑(當前文件)和播放 state(播放/暫停)。 第二個線程的工作是檢測這種變化,並通過改變、播放或暫停歌曲來采取相應的行動。

我有一個問題(我假設)正在發生的事情是第二個線程在讀取這些數據的同時被主線程寫入,這會產生亂碼 output。 我嘗試實現一個條件變量,但 output 仍然很糟糕。

這是我編寫數據的代碼:

extern pthread_mutex_t mutex;
extern pthread_cond_t cond;

pthread_mutex_lock(&mutex);

strcpy(audio->audio_path, state->cur_play_dir);
strcat(audio->audio_path, "/");
strcat(audio->audio_path, state->cur_play_file);
audio->play_state = MUSIC_PLAY;

pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);

這是我閱讀它的代碼:

extern pthread_mutex_t mutex;
extern pthread_cond_t cond;

while (1)
{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond, &mutex);

    char *new_audio_path = audio->audio_path;
    if (strcmp(new_audio_path, cur_audio_path))
    {               
        cur_audio_path = realloc(cur_audio_path,
                                strlen(new_audio_path) + 1);

        strcpy(cur_audio_path, audio->audio_path);
        printw("PATH: %s\n", cur_audio_path);
    }

    pthread_mutex_unlock(&mutex);
}

互斥鎖和條件被聲明為全局變量,如下所示:

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

我對並行編程相當陌生,所以我懷疑我正在做一些非常明顯和愚蠢的事情。

在這個問題上睡覺后,我意識到我的錯誤。 事實證明,存儲在路徑字符串中的數據實際上根本沒有問題。

在第二個線程中,我打印到 stdout 的路徑值純粹是為了檢查該值是否有效(所以我忘了鎖定任何東西)。 但是,在主線程中,我還將其他數據打印到標准輸出。

由於兩個線程都寫入標准輸出,打印時數據出現亂碼,而實際上存儲在 memory 中的數據沒有問題。 我通過在第一個線程寫入標准輸出時寫入第二個線程中的文本文件來驗證這一點。 寫入文本文件的數據沒有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM