Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty while synchronization in c++?

static char szInfo[256];
static volatile bool bIsLocked = false;

static void ApiFunc() {
    while (bIsLocked) { }
    bIsLocked = true;
    //do something to szInfo
    bIsLocked = false;
}

It has been awhile since I have done any threading in C++, Is this safe enough? This is a much simpler solution to me than using a mutex, but why would I use windows mutex instead?

like image 595
Tom Fobear Avatar asked Feb 05 '26 02:02

Tom Fobear


1 Answers

You would use a mutex (or more likely a critical section) because that would work. This code does not synchronise. Multiple threads can enter the critical region.

And of course, real locks don't spin. Well, spin-locks do, but you need a deep understanding of the performance implications of a spin-lock before electing to use one.

like image 144
David Heffernan Avatar answered Feb 06 '26 15:02

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!