互斥锁是一种同步机制,用于保护共享资源不被多个线程同时访问。当一个线程获得互斥锁时,其他试图获得该锁的线程将被阻塞,直到锁被释放。
优势:
类型:
应用场景:
示例代码:
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int shared_data = 0;
void* thread_func(void* arg) {
pthread_mutex_lock(&mutex);
shared_data++;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread_func, NULL);
pthread_create(&thread2, NULL, thread_func, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Shared data: %d\n", shared_data);
return 0;
}
读写锁允许多个线程同时读取共享资源,但只允许一个线程写入。这种锁适用于读操作远多于写操作的场景。
优势:
类型:
应用场景:
示例代码:
#include <pthread.h>
#include <stdio.h>
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
int shared_data = 0;
void* reader(void* arg) {
pthread_rwlock_rdlock(&rwlock);
printf("Read: %d\n", shared_data);
pthread_rwlock_unlock(&rwlock);
return NULL;
}
void* writer(void* arg) {
pthread_rwlock_wrlock(&rwlock);
shared_data++;
printf("Write: %d\n", shared_data);
pthread_rwlock_unlock(&rwlock);
return NULL;
}
int main() {
pthread_t reader_thread1, reader_thread2, writer_thread;
pthread_create(&reader_thread1, NULL, reader, NULL);
pthread_create(&reader_thread2, NULL, reader, NULL);
pthread_create(&writer_thread, NULL, writer, NULL);
pthread_join(reader_thread1, NULL);
pthread_join(reader_thread2, NULL);
pthread_join(writer_thread, NULL);
return 0;
}
当两个或多个线程互相等待对方释放资源时,就会发生死锁。
原因:
解决方法:
示例代码(使用超时机制):
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* thread_func(void* arg) {
int result = pthread_mutex_trylock(&mutex);
if (result == 0) {
// 成功获取锁
pthread_mutex_unlock(&mutex);
} else if (result == EBUSY) {
// 锁已被占用,处理超时情况
printf("Failed to acquire lock, try again later.\n");
} else {
// 其他错误
perror("pthread_mutex_trylock");
}
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread_func, NULL);
pthread_create(&thread2, NULL, thread_func, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
通过合理使用互斥锁和读写锁,并注意避免常见的并发问题,可以有效提高多线程程序的性能和稳定性。
领取专属 10元无门槛券
手把手带您无忧上云