℡Wang Yan 2018-11-05 04:13 采纳率: 100%
浏览 267

避免与 pthreads 发生内存冲突

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.

转载于:https://stackoverflow.com/questions/53148257/avoiding-memory-collisions-with-pthreads

  • 写回答

1条回答 默认 最新

  • ~Onlooker 2018-11-05 04:34
    关注

    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) ;
    }
    
    评论

报告相同问题?