避免与pthread发生内存冲突

时间:2018-11-05 04:13:50

标签: c pthreads

我是pthread的新手,我试图了解如何使用并发线程写入相同的全局变量来避免出现问题。这是最简单的示例:

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

当我执行此代码时,有时会打印200,有时会打印100,这意味着在后一种情况下,我认为两个线程都试图在同一时间写入“ sum”,并且一个线程被阻塞。

在我的实际应用程序中,“ sum”可能是一个大数组,一个线程可能正在尝试更新一个元素,而另一个线程通常正在尝试更新同一数组的另一个元素。

最简单/最简单的方法来确保对全局变量或数组进行的所有预期的读/写操作成功或至少验证该操作是否成功?不必保留操作顺序。

1 个答案:

答案 0 :(得分:0)

我似乎已经找到了答案-以前我对互斥量一无所知,直到有人提到它来回答另一个问题:

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) ;
}
相关问题