pthread_mutex_lock是一個函數,用于鎖定一個mutex(互斥鎖),以確保在多線程并發情況下對共享資源進行安全訪問。以下是一個簡單的例子:
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
void* my_thread_func(void* arg){
pthread_mutex_lock(&my_mutex); //先鎖定互斥鎖
printf("Thread ID: %ld entering critical section.\n", pthread_self());
// 在這里寫入共享資源的數據操作
printf("Thread ID: %ld leaving critical section.\n", pthread_self());
pthread_mutex_unlock(&my_mutex); //解鎖互斥鎖
return NULL;
}
int main(){
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, my_thread_func, NULL);
pthread_create(&thread2, NULL, my_thread_func, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
在這個例子中,我們使用了一個名為my_mutex的mutex來保護共享資源。my_thread_func是我們想要在線程上執行的函數,它包含了一些對共享資源的操作。
在my_thread_func中,我們首先調用pthread_mutex_lock(&my_mutex)來鎖定互斥鎖。這會阻止其他線程訪問共享資源,直到我們完成我們的操作并解鎖互斥鎖。在這里寫入共享資源的數據操作后,我們調用了pthread_mutex_unlock(&my_mutex)來釋放互斥鎖,以便其他線程可以訪問共享資源。
在主函數中,我們創建了兩個線程并等待它們的退出。在這個例子中,我們使用互斥鎖來確保只有一個線程在任何給定時間訪問共享資源。這可以避免數據競爭和其它并發相關問題。