在Linux C编程中,临界资源指的是在同一时刻只能被一个进程或线程访问的资源。如果多个进程或线程同时访问临界资源,可能会导致数据不一致、竞态条件等问题。因此,对临界资源的访问需要进行同步控制,以确保系统的正确性和稳定性。
以下是一个使用互斥锁保护临界资源的简单示例:
#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 5
int counter = 0;
pthread_mutex_t mutex;
void* increment(void* arg) {
for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&mutex); // 进入临界区
counter++;
pthread_mutex_unlock(&mutex); // 离开临界区
}
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
pthread_mutex_init(&mutex, NULL);
for (int i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, increment, NULL);
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
printf("Counter value: %d
", counter);
pthread_mutex_destroy(&mutex);
return 0;
}
通过合理使用同步机制,可以有效保护临界资源,确保系统的正确性和稳定性。
没有搜到相关的文章