即使每个线程操作自己的数据,是否有任何 cpp 函数或对象(不包括从 c 继承的)也不是线程安全的?
抱歉标题很长,但我认为它很好地解释了我感兴趣的内容。例如,C 函数 strtok 在最坏的情况下不是线程安全的:),它使用全局状态。因此,即使在不同的数据上调用它,它也不是线程安全的。 所以我的问题是“C++ minus C”中是否有函数存在同样的问题。 同样,我对“如果你从 10 个线程写入同一个文件,这是未定义的行为”之类的事情不感兴趣。我感兴趣的是“如果你从 2 个 diff 线程写入 2 个 diff 文件(每个线程写入自己的文件),那么这不是线程安全的。”
Sorry for the long title, but I think it explains well what I'm interested in. For example C function strtok is not thread safe in worst possible way :) , it uses a global state. So even if it is called on different data it is not thread safe.
So my question is are there functions in "C++ minus C" that have same problem.
Again I'm not interested in things like "if you write to same file from 10 threads it is undefined behavior". What I'm interested is "if you write to 2 diff files from 2 diff threads (each thread writes to its own file )that is not thread safe."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
线程安全仅由 C++11 真正涵盖; C++03 没有指定多线程行为。
在 C++11 中,相关位是 1.10/8“某些库调用与另一个线程执行的其他库调用同步。例如,原子存储-释放与需要的加载-获取同步其商店价值 (29.3)。”特别是§17.6.5.9 数据竞争避免。
您提到的情况显然是不允许的:“
上面的文字说“除非另有说明”,它包括一些 C 函数,例如 (27.9.2/2) “调用函数
tmpnam
NULL
参数可能会与使用NULL
参数对tmpnam
的其他调用引入数据争用 (17.6.5.9)。”Thread safety is only really covered by C++11; C++03 didn't specify multi-threaded behavior.
In C++11, the relevant bits are 1.10/8 "Certain library calls synchronize with other library calls performed by another thread. For example, an atomic store-release synchronizes with a load-acquire that takes its value from the store (29.3)." and especially §17.6.5.9 Data race avoidance.
The cases you mention are obviously disallowed: "
Where the text above says "unless otherwise specified", it includes some C function, e.g. (27.9.2/2) "Calls to the function
tmpnam
with an argument ofNULL
may introduce a data race (17.6.5.9) with other calls totmpnam
with an argument ofNULL
."C++ 标准不保证 new(或 malloc())是线程安全的。尽管让它们线程安全非常重要。
但是,大多数平台都支持线程安全
new
。C++ standard doesn't guarantee
new
(ormalloc()
) to be thread-safe. Even though it's very crucial to have them thread-safe.However, most platforms support thread-safe
new
.实际上,C++ 区分了“只读线程安全”和“完全线程安全”。例如,所有 std 容器都是“只读”线程安全的,并且如果任何线程修改容器,则不安全。
但是,当您不访问共享数据时,我不记得有任何 C++ 功能是不安全的。
Actually, C++ differentiates between "read-only thread safety" and "full thread safety". E.g. all std containers are "read-only" thread-safe and not safe if any of the threads modifies the container.
However, when you do not access shared data, I don't recall any of C++ features being unsafe.