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

pthread 互斥鎖實現多線程安全訪問共享資源

     編輯:C++ 入門

pthread 互斥鎖同步機制詳解與實戰

多線程共享內存模型下,對共享變量的並發寫入會導致數據競爭。pthread 提供 pthread_mutex_t 互斥鎖,通過 lock/unlock 配對保證臨界區原子性。

完整示例:多線程向 vector 安全添加元素

#include 
#include 
#include 
using namespace std;

vector vec;
pthread_mutex_t mutex;
int thread_count = 4;

void* hello(void* arg) {
    int id = (long)arg;
    pthread_mutex_lock(&mutex);   // 加鎖
    vec.push_back(id);
    pthread_mutex_unlock(&mutex); // 解鎖
    return nullptr;
}

int main() {
    pthread_t threads[4];
    pthread_mutex_init(&mutex, NULL);
    for (long i = 0; i < thread_count; i++)
        pthread_create(&threads[i], NULL, hello, (void*)i);

    cout << "Main thread waiting..." << endl;
    for (int i = 0; i < thread_count; i++)
        pthread_join(threads[i], NULL);

    for (int v : vec) cout << v << endl;
    pthread_mutex_destroy(&mutex);
    return 0;
}

關鍵點

  • 鎖必須全局/靜態初始化(pthread_mutex_init),銷毀前確保無線程持有。
  • 臨界區應盡量短,避免死鎖與性能下降。
  • C++11 建議優先使用 std::mutex + std::lock_guard,RAII 風格更安全。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved