multithreading - C - Can global pointers be modified by different threads? -
do global pointers have scope exist between threads?
for instance, suppose have 2 files, file1.c , file2.c:
file1.c:
uint64_t *g_ptr = null; modify_ptr(&g_ptr) { //code modify g_ptr point valid address } read_from_addr() { //code uses g_ptr read values memory it's pointing }
file2.c:
function2a() { read_from_addr(); }
so have threada runs through file1.c , executes modify_ptr(&g_ptr) , read_from_addr(). , threadb runs, , runs through file2.c executing function2a().
my question is: threadb see g_ptr modified? or still see it's pointing null?
if that's not case, mean pointer global? , how ensure pointer accessible between different threads?
please let me know if need clarify anything. thanks
my question is: threadb see g_ptr modified? or still see it's pointing null?
maybe. if accessed without sort of external synchronization, you're see bizarre, highly non-reproducible results -- in cases, compiler may make optimizations based on analysis of code can stem assuming variable not modified during code paths. example, consider code:
// global variable int global = 0; // thread 1 runs code: while (global == 0) { // nothing } // thread 2 @ point this: global = 1;
in case, compiler can see global
not modified inside while
loop, , doesn't call external functions, can "optimize" this:
if (global == 0) { while (1) { // nothing } }
adding volatile
keyword declaration of variable prevents compiler making optimization, not intended use case of volatile
when c language standardized. adding volatile
here slow down program in small ways , mask real problem -- lack of proper synchronization.
the proper way manage global variables need accessed simultaneously multiple threads use mutexes protect them1. example, here's simple implementation of modify_ptr
using posix threads mutex:
uint64_t *g_ptr = null; pthread_mutex_t g_ptr_mutex = pthread_mutex_initializer; void modify_ptr(uint64_t **ptr, pthread_mutex_t *mutex) { // lock mutex, assign pointer new value, unlock mutex pthread_mutex_lock(mutex); *ptr = ...; pthread_mutex_unlock(mutex); } void read_from_addr() { modify_ptr(&g_ptr, &g_ptr_mutex); }
mutex functions ensure proper memory barriers inserted, changes made variable protected mutex propagated other cpu cores, provided every access of variable (including reads!) protected mutex.
1) can use specialized lock-free data structures, advanced technique , easy wrong
Comments
Post a Comment