萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 多執行緒互斥鎖 實戰範例:pthread_mutex 同步化存取共享資源

程式碼完整範例

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

pthread_mutex_t Device_mutex;
int count = 0;

void* thread_func1(void* arg)
{
    while (1)
    {
        pthread_mutex_lock(&Device_mutex);
        printf("thread1: %d\n", count);
        pthread_mutex_unlock(&Device_mutex);
        count++;
        sleep(1);
    }
    return NULL;
}

void* thread_func2(void* arg)
{
    while (1)
    {
        pthread_mutex_lock(&Device_mutex);
        printf("thread2: %d\n", count);
        pthread_mutex_unlock(&Device_mutex);
        count++;
        sleep(1);
    }
    return NULL;
}

int main()
{
    pthread_t thread1, thread2;
    pthread_mutex_init(&Device_mutex, NULL);

    if (pthread_create(&thread1, NULL, thread_func1, NULL) == -1)
    {
        printf("create thread1 error!\n");
        exit(1);
    }
    sleep(1);

    if (pthread_create(&thread2, NULL, thread_func2, NULL) == -1)
    {
        printf("create thread2 error!\n");
        exit(1);
    }
    sleep(1);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    pthread_mutex_destroy(&Device_mutex);
    return 0;
}

關鍵點解析

  • 互斥鎖初始化: pthread_mutex_init(&Device_mutex, NULL) 建立鎖。
  • 加鎖/解鎖: pthread_mutex_lock / pthread_mutex_unlock 保護臨界區(列印與遞增 count)。
  • 執行緒建立: pthread_create 傳入函數指標,注意型別轉換。
  • 等待結束: pthread_join 阻塞主執行緒直到子執行緒結束(此範例為無限迴圈,實際應用需加入退出機制)。
  • 資源釋放: pthread_mutex_destroy 銷毀鎖。

編譯與執行

gcc -o mutex_demo mutex_demo.c -lpthread
./mutex_demo

輸出將交替顯示 thread1: N 與 thread2: N+1,證明共享變數 count 在鎖保護下安全存取。

copyright © 萬盛學電腦網 all rights reserved