在C語言中,多線程訪問全局變量需要注意線程同步問題,以避免出現(xiàn)數(shù)據(jù)競(jìng)爭(zhēng)和不確定的結(jié)果。以下是幾種常見的方法:
#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);
// 創(chuàng)建線程
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
// 等待線程結(jié)束
pthread_join(thread, NULL);
// 銷毀互斥鎖
pthread_mutex_destroy(&mutex);
return 0;
}
#include <pthread.h>
#include <semaphore.h>
int global_variable;
sem_t sem;
void* thread_function(void* arg) {
// 等待信號(hào)量
sem_wait(&sem);
// 訪問全局變量
global_variable++;
// 釋放信號(hào)量
sem_post(&sem);
return NULL;
}
int main() {
// 初始化信號(hào)量
sem_init(&sem, 0, 1);
// 創(chuàng)建線程
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
// 等待線程結(jié)束
pthread_join(thread, NULL);
// 銷毀信號(hào)量
sem_destroy(&sem);
return 0;
}
#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);
// 創(chuàng)建線程
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
// 修改全局變量,并發(fā)送條件變量通知
pthread_mutex_lock(&mutex);
global_variable++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
// 等待線程結(jié)束
pthread_join(thread, NULL);
// 銷毀互斥鎖和條件變量
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
通過以上方法,可以確保多個(gè)線程能夠安全地訪問全局變量,避免數(shù)據(jù)競(jìng)爭(zhēng)和不確定的結(jié)果。