Stream synchronization with mixed C and C ++

I have a multi-threaded program with a main thread that is third-party (cannot change it) and pure C. My task is to create new modules on it (in C ++), which are partially located in other threads and need to use the C programming interface Basically just reading some variables (ints, float, nothing complicated) that are saved and updated in stream C.

Now to my question: how can I make sure that I do not get garbage from the C interface when accessing these variables, since I can not use the mutex to lock it while reading. Is it possible? Or writes a float / int atomic operation?

+4
source share
4 answers

You can not. Reading and writing nothing is an atomic operation, and if you cannot change the C code, you're out of luck. Synchronization always requires both parts to be synchronized.

It is best to ask a third party to make their part safe and / or share a blocking mechanism with you.

0
source

Statements like "record float / int [is] an atomic operation anyway", unfortunately, are not defined in C or C ++ (although using std::atomicC11 11 and stdatomic.h methods from C11 may help here, but it won't help you with C interop for a library that you cannot change, so you can probably ignore it here).

- , , , , 32- 64- , , .

. , POSIX/pthreads, mutexes pthreads - C ++, , .

C, , , ++ C, . , C, / , , - , , d , API C.

+5

. - , C, . , - - .

, .

+3

, , , , . , - .

, , , , . .

int myVal = 0;

int main() {
  while(!shouldQuit()) {
    doSomeIndependentStuff();
    pthread_lock(&mutex);
    myVal = independentGlobalVal;
    pthread_unlock(&mutex);
  }
}

int getMyVal() {
  int retVal = 0;
  pthread_lock(&mutex);
  retVal  = myVal;
  pthread_unlock(&mutex);
  return retval;
}
+1

All Articles