面试题答案
一键面试- 措施:
- 在C语言多线程编程中,当多个线程需要访问和修改同一个全局变量时,为避免数据竞争,可以使用互斥锁(mutex)、信号量、读写锁等同步机制。其中互斥锁是一种常用的简单方法,它通过锁定和解锁机制来保证同一时间只有一个线程能访问共享资源(这里的全局变量)。
- 代码示例:
#include <stdio.h>
#include <pthread.h>
// 定义全局变量
int global_variable = 0;
// 定义互斥锁
pthread_mutex_t mutex;
// 线程函数
void* increment(void* arg) {
// 加锁
pthread_mutex_lock(&mutex);
for (int i = 0; i < 1000000; i++) {
global_variable++;
}
// 解锁
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
pthread_t thread1, thread2;
// 创建线程1
if (pthread_create(&thread1, NULL, increment, NULL) != 0) {
printf("\n ERROR creating thread1");
return 1;
}
// 创建线程2
if (pthread_create(&thread2, NULL, increment, NULL) != 0) {
printf("\n ERROR creating thread2");
return 2;
}
// 等待线程1结束
if (pthread_join(thread1, NULL) != 0) {
printf("\n ERROR joining thread");
return 3;
}
// 等待线程2结束
if (pthread_join(thread2, NULL) != 0) {
printf("\n ERROR joining thread");
return 4;
}
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
printf("Final value of global_variable: %d\n", global_variable);
return 0;
}
在上述代码中:
- 首先定义了一个全局变量
global_variable
和一个互斥锁mutex
。 - 在
increment
线程函数中,通过pthread_mutex_lock
对互斥锁加锁,这样在同一时间只有一个线程能进入for
循环修改global_variable
,操作完成后通过pthread_mutex_unlock
解锁。 - 在
main
函数中,初始化互斥锁,创建两个线程去调用increment
函数,等待两个线程执行完毕后,销毁互斥锁并输出global_variable
的最终值。这样通过互斥锁就有效地避免了多线程访问全局变量时的数据竞争问题。