csdnceshi62 2018-11-05 04:13 采纳率: 100%
浏览 253

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

  • from.. 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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置