可以在一个整数线程之间共享的安全? [英] Can an integer be shared between threads safely?

查看:104
本文介绍了可以在一个整数线程之间共享的安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有使用多线程的pthreads之间相同的整数内存位置在C程序中没有任何同步实用程序的问题?

Is there a problem with multiple threads using the same integer memory location between pthreads in a C program without any synchronization utilities?

为了简化问题,


  • 只有一个线程将会写入整数

  • 多个线程将读取整数

这伪C说明我在想什么。

This pseudo-C illustrates what I am thinking

void thread_main(int *a) {
  //wait for something to finish
  //dereference 'a', make decision based on its value
}

int value = 0;

for (int i=0; i<10; i++)
  pthread_create(NULL,NULL,thread_main,&value);
}
// do something
value = 1;

我认为它是安全的,因为一个整数占用一个字处理器,和读/写一个字应该是最原子操作的,对吧?

I assume it is safe, since an integer occupies one processor word, and reading/writing to a word should be the most atomic of operations, right?

推荐答案

您伪code不是安全的。

Your pseudo-code is NOT safe.

虽然访问一个字大小的整数确实是原子,这意味着你永远不会看到一个中间值,但无论是写之前或写入后,这是不够的,你介绍的算法。

Although accessing a word-sized integer is indeed atomic, meaning that you'll never see an intermediate value, but either "before write" or "after write", this isn't enough for your outlined algorithm.

您是靠着写的相对顺序上 A ,使在唤醒线程一些其他的变化。这不是一个原子操作,并不能保证在现代处理器。

You are relying on the relative order of the write to a and making some other change that wakes the thread. This is not an atomic operation and is not guaranteed on modern processors.

您需要某种形式的存储栅栏,以prevent写重新排序。否则,不能保证其他线程曾经看到新的数值。

You need some sort of memory fence to prevent write reordering. Otherwise it's not guaranteed that other threads EVER see the new value.

这篇关于可以在一个整数线程之间共享的安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆