pthread_mutex_lock 是一个用于锁定互斥锁的函数,它属于 POSIX 线程库 (pthread)
以下是 pthread_mutex_lock 的正确使用方法:
pthread_mutex_init 函数进行初始化:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;// 或者pthread_mutex_t mutex;pthread_mutex_init(&mutex, NULL);在访问共享资源之前,使用 pthread_mutex_lock 对互斥锁进行加锁:pthread_mutex_lock(&mutex);在访问共享资源之后,使用 pthread_mutex_unlock 对互斥锁进行解锁:pthread_mutex_unlock(&mutex);当不再需要互斥锁时,使用 pthread_mutex_destroy 函数将其销毁:pthread_mutex_destroy(&mutex);请注意,在使用互斥锁时,务必确保在访问共享资源之前加锁,并在访问完成后解锁。这样可以确保同一时间只有一个线程能够访问共享资源,从而避免竞态条件和数据不一致的问题。
以下是一个简单的示例,展示了如何使用 pthread_mutex_lock:
#include<stdio.h>#include <stdlib.h>#include <pthread.h>#define NUM_THREADS 5int counter = 0;pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;void *thread_function(void *arg) { int i; for (i = 0; i < 100000; i++) { pthread_mutex_lock(&mutex); counter++; pthread_mutex_unlock(&mutex); } return NULL;}int main() { pthread_t threads[NUM_THREADS]; int i; for (i = 0; i < NUM_THREADS; i++) { pthread_create(&threads[i], NULL, thread_function, NULL); } for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf("Counter: %d\n", counter); pthread_mutex_destroy(&mutex); return 0;}在这个示例中,我们创建了 5 个线程,每个线程都会对全局变量 counter 进行 100,000 次自增操作。通过使用互斥锁,我们确保了在任何时候只有一个线程能够访问 counter,从而避免了竞态条件和数据不一致的问题。


