多線程共享內存模型下,對共享變量的並發寫入會導致數據競爭。pthread 提供 pthread_mutex_t 互斥鎖,通過 lock/unlock 配對保證臨界區原子性。
#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),銷毀前確保無線程持有。std::mutex + std::lock_guard,RAII 風格更安全。