0
votes

I'm brand new to pthreads, and I'm trying to understand what can be done to avoid problems when using simultaneous threads to write to the same global variables. Here's the simplest possible example:

pthread_t tid1, tid2 ;

int sum = 0 ;

void process()
{
  for (int i ; i<100; i++)
    sum += 1 ;
}

int main()
{

  pthread_create(&tid1, NULL, (void *) process,  NULL ) ;
  pthread_create(&tid2, NULL, (void *) process,  NULL ) ;

  pthread_join(tid1, NULL) ;
  pthread_join(tid2, NULL) ;

  printf("Sum = %d\n", sum) ;
}

When I execute this code, it sometimes prints 200 and sometimes prints 100, implying in the latter case, I assume, that both threads were trying to write to 'sum' at exactly the same time, and one thread got blocked.

In my real world application, 'sum' might be a large array, and one thread might be trying to update one element while another is usually trying to update a different element of the same array.

What is the simplest/cleanest way to ensure that all intended read/write operations on a global variable or array succeed or at least to verify whether the operation succceeded? It isn't necessary to preserve the order of operation.

1
Updating different elements of an array at the same time is allowed. - user253751
I was under the impression that a whole block of memory could become inaccessible when one element is being accessed -- is this incorrect? - Grant Petty
Yes, that is incorrect. Only accessing the same location causes a problem. - user253751

1 Answers

0
votes

I seem to have found an answer -- I had not previously known about mutex until it was mentioned in response to a different question:

pthread_t tid1, tid2 ;
pthread_mutex_t lock;

int sum = 0 ;

void process()
{
  for (int i ; i<100; i++) {
    pthread_mutex_lock(&lock);
    sum += 1 ;
    pthread_mutex_unlock(&lock);
  }
}

int main()
{
  if (pthread_mutex_init(&lock, NULL) != 0)
    {
      printf("\n mutex init failed\n");
      return 1;
    }

  pthread_create(&tid1, NULL, (void *) process,  NULL ) ;
  pthread_create(&tid2, NULL, (void *) process,  NULL ) ;

  pthread_join(tid1, NULL) ;
  pthread_join(tid2, NULL) ;

  pthread_mutex_destroy(&lock);

  printf("Sum = %d\n", sum) ;
}