Simultaneous access to a variable in c

I have a pretty specific question about parallel programming in C. I have done quite a bit of research on this, but have seen some conflicting answers, so I hope for some clarification. I have a program, something like the following (sorry for the long block of code):

typedef struct {
  pthread_mutex_t mutex;
  /* some shared data */
  int eventCounter;
} SharedData;

SharedData globalSharedData;

typedef struct {
  /* details unimportant */
} NewData;

void newData(NewData data) {
  int localCopyOfCounter;

  if (/* information contained in new data triggers an
         event */) {
    pthread_mutex_lock(&globalSharedData.mutex);
    localCopyOfCounter = ++globalSharedData.eventCounter;
    pthread_mutex_unlock(&globalSharedData.mutex);
  }
  else {
    return;
  }

  /* Perform long running computation. */

  if (localCopyOfCounter != globalSharedData.eventCounter) {
    /* A new event has happened, old information is stale and
       the current computation can be aborted. */
    return;
  }

  /* Perform another long running computation whose results
     depend on the previous one. */

  if (localCopyOfCounter != globalSharedData.eventCounter) {
    /* Another check for new event that causes information
       to be stale. */
    return;
  }

  /* Final stage of computation whose results depend on two
     previous stages. */
}

, , newData. , , , : , , CPU, , . , ( , , , , ). eventCounter SharedData , - ? ?

+5
3

, C concurrency. (gcc msvc, ) - . , , , , . , .

, , eventCounter volatile. , , eventCounter.

int load_acquire(volatile int * counter) { return *counter; }

if (localCopy != load_acquire(&sharedCopy))
    // ...
+2

"", . (no concurrency).

, .

0

intrinsics, , ++ - - .

volatile useless , , , .

, , . , , OpenMP MPI ( ), , , ... , , intel TBB API Microsoft, , , , cmpxchg8b, , ...

.

0

All Articles