首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Linux C 編程:執行緒互斥鎖 pthread_mutex 完整範例

     編輯:關於C語言

互斥鎖核心 API

函數用途
pthread_mutex_init(&mutex, NULL)初始化互斥鎖
pthread_mutex_lock(&mutex)鎖定(阻塞直到取得)
pthread_mutex_unlock(&mutex)解鎖
pthread_mutex_destroy(&mutex)銷毀互斥鎖

完整範例:兩執行緒安全遞增共享變數

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

static int value = 0;
pthread_mutex_t mutex;

void *func(void *arg) {
    while (1) {
        pthread_mutex_lock(&mutex);
        sleep(1);              // 模擬工作
        value++;
        printf("value = %d\n", value);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main(void) {
    pthread_t tid1, tid2;
    pthread_mutex_init(&mutex, NULL);

    pthread_create(&tid1, NULL, func, NULL);
    pthread_create(&tid2, NULL, func, NULL);

    while (1) sleep(1);  // 主執行緒等待
    return 0;
}

編譯指令

gcc mutex.c -o mutex -lpthread

必須連結 pthread 庫。輸出將交替顯示兩執行緒遞增的值,無競爭條件。

關鍵點

  • 共享資料 value 必須受互斥鎖保護
  • sleep(1) 在鎖定區內,確保交替執行可見
  • 實際應用中鎖定區應盡量縮小,避免阻塞其他執行緒
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved