Access to a variable from two threads in C

I have the following code snippet:

int attempts = 0;
while(ptr== NULL && attempts < 60) {
        sleep(1000);
        attempts++;
    }

which continuously loops, waiting for the pointer to be set by another thread. Another thread will just do

ptr = //some value

My question is, is it safe? Will this affect memory corruption, which will make it difficult to debug errors?

PS: I know that the compiler can optimize ptr due to the lack of the volatile keyword. It doesn't matter to me. My only concern is that this will cause problems for other unrelated pieces of code.

+4
source share
3 answers

, ptr volatile; . . C11 <stdatomic.h> . GCC , . , ( " " ) ptr !

( ) , , undefined ( , ..).

, x86 , UB

/ .

semaphore.

GCC ( 4.9) -fsanitize=thread / -fsanitize=address ( ), .

, . valgrind, ( -g, gcc -O1 -g, ).

( 4.9 GCC - 2014 , binutils, gdb, libc, ​​....)

+2

, . C . , , - , , , . , , , , - undefined. . , .

, , . , , , , , , , BIOS - .

+3

As far as I know, no. This is unsafe and may lead to incompatible readings. The best way is to protect the ptr variable with a mutex or binary semaphore. Check mutex.h for mutex functions (e.g. mutex_init, mutex_lock, mutex_unlock, etc.).

0
source

All Articles