【问题标题】:Avoiding memory collisions with pthreads避免与 pthread 发生内存冲突
【发布时间】:2018-11-05 04:13:49
【问题描述】:

我是 pthreads 的新手,我试图了解在使用并发线程写入相同的全局变量时可以做些什么来避免出现问题。这是最简单的例子:

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”可能是一个大数组,一个线程可能会尝试更新一个元素,而另一个线程通常会尝试更新同一数组的不同元素。

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

【问题讨论】:

  • 允许同时更新数组的不同元素。
  • 我的印象是,当访问一个元素时,整块内存可能会变得不可访问——这不正确吗?
  • 是的,这是不正确的。只有访问相同的位置会导致问题。

标签: c pthreads


【解决方案1】:

我似乎找到了答案——我以前不知道互斥锁,直到在回答另一个问题时提到它:

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

【讨论】:

    猜你喜欢
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2021-09-30
    • 2011-06-26
    • 2013-10-01
    • 1970-01-01
    相关资源
    最近更新 更多