Linux同步互斥是指在多线程或多进程环境中,为了保证共享资源的正确访问和修改,而采取的一系列机制。同步是指协调多个进程或线程的执行顺序,互斥是指同一时间只允许一个进程或线程访问共享资源。
原因:多个进程或线程互相等待对方释放资源,导致程序无法继续执行。
解决方法:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void* thread_func(void* arg) {
pthread_mutex_lock(&mutex1);
printf("Thread locked mutex1\n");
sleep(1);
pthread_mutex_lock(&mutex2);
printf("Thread locked mutex2\n");
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
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);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
return 0;
}
参考链接:pthread_mutex_lock
原因:多个进程或线程在尝试获取资源时不断改变状态,但都无法成功获取资源。
解决方法:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* thread_func(void* arg) {
while (1) {
if (pthread_mutex_trylock(&mutex) == 0) {
printf("Thread locked mutex\n");
pthread_mutex_unlock(&mutex);
break;
} else {
printf("Thread failed to lock mutex, retrying...\n");
usleep(rand() % 100000); // Random sleep between 0 and 99999 microseconds
}
}
return NULL;
}
int main() {
srand(time(NULL));
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);
pthread_mutex_destroy(&mutex);
return 0;
}
Linux同步互斥机制在多线程和多进程编程中非常重要,可以确保共享资源的正确访问和修改。常见的同步互斥机制包括信号量、互斥锁、条件变量和读写锁。在实际应用中,需要注意避免死锁和活锁等问题,并采取相应的解决方法。
领取专属 10元无门槛券
手把手带您无忧上云