关于c++多线程全局变量访问
在多线程代码的测试过程中,可能会出现全局变量的访问冲突问题,可以通过引入锁(互斥锁、读写锁),获得锁定线程完成“读——修改——写”的操作后,释放锁给其他线程,没有获得锁的线程只能等待而不能访问,这样“读——修改——写”3步操作不会执行到中间被其他线程打断,可以完整的执行下去。
测试代码
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <string.h>
#include <cstdlib>
#define thread_lock_test 1
phread_mutex_t lock;
int gcn = 0; //定义一个全局变量,用于累加
void *thread_1(void *arg) { //第一个线程
#if thread_lock_test
pthread_mutex_lock(&lock); //锁定
#endif
int j;
for (j = 0; j < 1000000; j++) { //开始累加
gcn++;
}
#if thread_lock_test
pthread_mutex_unlock(&lock); //解锁
#endif
pthread_exit((void *)0);
}
void *thread_2(void *arg) { //第二个线程
#if thread_lock_test
pthread_mutex_lock(&lock);
#endif
int j;
for (j = 0; j < 1000000; j++) { //开始累加
gcn++;
}
#if thread_lock_test
pthread_mutex_unlock(&lock);
#endif
pthread_exit((void *)0);
}
int main(void)
{
#if thread_lock_test
pthread_mutex_init(&lock, NULL);
#endif
int j,err;
pthread_t th1, th2;
for (j = 0; j < 10; j++) //做10次测试
{
err = pthread_create(&th1, NULL, thread_1, (void *)0); //创建第1个线程
if (err != 0) {
printf("create new thread error:%s\n", strerror(err));
exit(0);
}
err = pthread_create(&th2, NULL, thread_2, (void *)0); //创建第2个线程
if (err != 0) {
printf("create new thread error:%s\n", strerror(err));
exit(0);
}
err = pthread_join(th1, NULL); //等待第一个线程结束
if (err != 0) {
printf("wait thread done error:%s\n", strerror(err));
exit(1);
}
err = pthread_join(th2, NULL); //等待第二个线程结束
if (err != 0) {
printf("wait thread done error:%s\n", strerror(err));
exit(1);
}
printf("gcn=%d\n", gcn);
gcn = 0;
}
return 0;
}
测试结果
取消锁定后,则上述代码可能无法完成所有的累加。