Thread-Safe Global Variables in C
In the C programming language, it is important to address thread synchronization issues when multiple threads access global variables to avoid data races and unpredictable results. Here are some common methods to do so:
- Using mutex: before accessing global variables, the thread first acquires the mutex, and then releases it after finishing the access. This ensures that only one thread can access global variables at a time.
#include <pthread.h>
int global_variable;
pthread_mutex_t mutex;
void* thread_function(void* arg) {
// 获取互斥锁
pthread_mutex_lock(&mutex);
// 访问全局变量
global_variable++;
// 释放互斥锁
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
// 创建线程
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
// 等待线程结束
pthread_join(thread, NULL);
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}
- Using semaphore: Set a semaphore to 1, before accessing the global variable, the thread first performs a P operation (wait), and after finishing the access, it performs a V operation (release).
#include <pthread.h>
#include <semaphore.h>
int global_variable;
sem_t sem;
void* thread_function(void* arg) {
// 等待信号量
sem_wait(&sem);
// 访问全局变量
global_variable++;
// 释放信号量
sem_post(&sem);
return NULL;
}
int main() {
// 初始化信号量
sem_init(&sem, 0, 1);
// 创建线程
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
// 等待线程结束
pthread_join(thread, NULL);
// 销毁信号量
sem_destroy(&sem);
return 0;
}
- Condition variables are used by setting up a condition variable and a mutex lock. Threads use the mutex lock to protect access to global variables. Before accessing, a thread waits for the condition variable to be met, and notifies other waiting threads through the condition variable after accessing is completed.
#include <pthread.h>
int global_variable;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* thread_function(void* arg) {
// 获取互斥锁
pthread_mutex_lock(&mutex);
// 等待条件变量满足
while (global_variable == 0) {
pthread_cond_wait(&cond, &mutex);
}
// 访问全局变量
global_variable++;
// 释放互斥锁
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
// 初始化互斥锁和条件变量
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
// 创建线程
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
// 修改全局变量,并发送条件变量通知
pthread_mutex_lock(&mutex);
global_variable++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
// 等待线程结束
pthread_join(thread, NULL);
// 销毁互斥锁和条件变量
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
By using the above methods, it is possible to ensure that multiple threads can safely access global variables, avoiding data races and unpredictable results.