我遇到需要跨线程访问共享内存中的变量的情况。变量是在许多地方的现有代码中最初定义并不断更新的。我添加的代码将允许此现有代码库作为后台线程运行,但是我需要从此共享变量中读取数据。
我的问题是,每次更新时,是否需要向现有代码库中添加互斥锁?或者我可以在读取数据时将互斥锁添加到新代码中。我在下面创建了以下似乎可以锻炼的小测试用例。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct my_data {
int shared;
}MY_DATA;
MY_DATA data;
pthread_mutex_t lock;
void *background(void *x_void_ptr)
{
int i = 0;
int sleep_time;
while(i < 10)
{
data.shared++;
printf("BACK thread, Data = %d\n", data.shared);
sleep_time = rand()%5;
sleep(sleep_time);
i++;
}
return NULL;
}
int main()
{
int sleep_time;
pthread_t bg_thread;
if(pthread_create(&bg_thread, NULL, background, NULL)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
MY_DATA *p_data = &data;
int i = 0;
while(i < 10)
{
pthread_mutex_lock(&lock);
printf("FOR thread, Data = %d\n", p_data->shared);
pthread_mutex_unlock(&lock);
sleep_time = rand()%5;
sleep(sleep_time);
i++;
}
// Finish up
if(pthread_join(bg_thread, NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
return 0;
}
输出:
FOR thread, Data = 0
BACK thread, Data = 1
BACK thread, Data = 2
FOR thread, Data = 2
FOR thread, Data = 2
BACK thread, Data = 3
BACK thread, Data = 4
BACK thread, Data = 5
FOR thread, Data = 5
BACK thread, Data = 6
BACK thread, Data = 7
BACK thread, Data = 8
FOR thread, Data = 8
FOR thread, Data = 8
BACK thread, Data = 9
FOR thread, Data = 9
BACK thread, Data = 10
FOR thread, Data = 10
FOR thread, Data = 10
FOR thread, Data = 10
运行多次后,看起来没有数据损坏(即,前台正在读取正确的数据),但是我的直觉是我需要在前台和后台代码中都包含互斥体。
将我的评论中的材料转换成答案。
请注意,进程之间的所有全局内存(线程本地存储和函数中的本地变量除外)在线程之间共享。共享内存是进程之间共享的内存的术语。
无论是线程还是进程正在访问内存,只要有多个执行线程可以同时访问同一内存,就需要确保对访问进行了适当的管理(例如,使用互斥锁)。如今,假设您的机器中只有一个核心在工作,这种情况已经很少见,因此,潜在的并发访问已成为常态。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句