larry*wei 2018-11-05 04:13 采纳率: 0%
浏览 229

避免与 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条回答 默认 最新

  • 北城已荒凉 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) ;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题