互斥锁是一种同步机制,用于保护共享资源不被多个线程同时访问。当一个线程获得互斥锁时,其他试图获得该锁的线程将被阻塞,直到锁被释放。
优势:
类型:
应用场景:
信号量是一种计数器,用于控制多个线程或进程对共享资源的访问。它可以用来实现互斥锁,也可以用来控制对一组资源的访问。
优势:
类型:
应用场景:
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex;
int shared_data = 0;
void* thread_func(void* arg) {
pthread_mutex_lock(&mutex);
shared_data++;
printf("Thread %ld: shared_data = %d\n", (long)arg, shared_data);
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t threads[5];
pthread_mutex_init(&mutex, NULL);
for (long i = 0; i < 5; ++i) {
pthread_create(&threads[i], NULL, thread_func, (void*)i);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
return 0;
}
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
sem_t sem;
int shared_data = 0;
void* thread_func(void* arg) {
sem_wait(&sem);
shared_data++;
printf("Thread %ld: shared_data = %d\n", (long)arg, shared_data);
sem_post(&sem);
return NULL;
}
int main() {
pthread_t threads[5];
sem_init(&sem, 0, 1); // Initialize semaphore with value 1
for (long i = 0; i < 5; ++i) {
pthread_create(&threads[i], NULL, thread_func, (void*)i);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
sem_destroy(&sem);
return 0;
}
原因:
解决方法:
原因:
解决方法:
原因:
解决方法:
pthread_rwlock_t
),允许多个读操作并发执行。通过以上方法,可以有效管理和优化Linux环境中的互斥锁和信号量使用。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云