请问C++的new和delete操作符是否线程安全?

luo6620378xu 2013-01-21 10:44:28
请问C++的new和delete操作符是否线程安全?

按照我的理解,有可能是线程不安全的。因为有的版本的new和delete是用
malloc和free实现的。这里应该指的是operator new 和operator delete。

而new operator和delete operator有C++自己的语义。

所以我的疑问就是:
C++的new和delete操作符是否线程安全?


谢谢!


...全文
1564 14 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
youyou1912 2013-01-31
  • 打赏
  • 举报
回复
luo6620378xu 2013-01-23
  • 打赏
  • 举报
回复
引用 7 楼 zhao4zhong1 的回复:
线程安全不安全还决定于链接的是否支持多线程的库。
嗯,有道理。所以才来问到底线程安全还是不安全。标准不知道有没有说明 我用的是gnu的libc库
taodm 2013-01-23
  • 打赏
  • 举报
回复
赵老师已在7楼开了金口。结贴吧。
luo6620378xu 2013-01-23
  • 打赏
  • 举报
回复
引用 6 楼 gykgod 的回复:
Although the memory is on the heap, the pointer to it is on the stack. Only your thread has the pointer to this memory, and so there is no risk of concurrent modification - no other threa……
额,谢谢你的回答。但是我的问题不是这样。 我是想知道,malloc和free这两个函数是否线程安全。 单个线程在堆上分配的内存肯定是自己用,无需加锁保护。
ppsharp 2013-01-22
  • 打赏
  • 举报
回复
reentrant
sublimepan 2013-01-22
  • 打赏
  • 举报
回复 1
new delete是线程安全的,有书籍明确指出的。
crazy_samba 2013-01-21
  • 打赏
  • 举报
回复
难道你认为malloc/free是线程不安全的。 new/delete/malloc/free都是线程安全的。
引用 楼主 luo6620378xu 的回复:
按照我的理解,有可能是线程不安全的。因为有的版本的new和delete是用 malloc和free实现的。
bravery36 2013-01-21
  • 打赏
  • 举报
回复
以前的编译器我不清楚,现在的编译器的话new和delete应该是线程安全的吧,不然程序猿不用混了。
chuachua66 2013-01-21
  • 打赏
  • 举报
回复
根源不知道,但从实践上说,我用的一直是没出过问题。
waterbright 2013-01-21
  • 打赏
  • 举报
回复
我觉得是线程不安全的。 在分配内存的时候如果切换去做其他事情,可能导致分配出问题。 在多线程的时候,还是弄个临界区、互斥量什么的确保一下吧。
赵4老师 2013-01-21
  • 打赏
  • 举报
回复
线程安全不安全还决定于链接的是否支持多线程的库。
gykgod 2013-01-21
  • 打赏
  • 举报
回复
Although the memory is on the heap, the pointer to it is on the stack. Only your thread has the pointer to this memory, and so there is no risk of concurrent modification - no other thread knows where the memory is to modify it. You would only get a problem with thread safety if you were to pass this pointer to another thread that would then concurrently modify this memory at the same time as your original (or another) thread.
疯狂的红豆 2013-01-21
  • 打赏
  • 举报
回复
C++语义中的new/delete两个关键字应该都是封装了malloc/free的。这些函数都是经过编译器向操作系统进行申请内存的,除非是编译器的设计问题,否则应该是安全的。
luo6620378xu 2013-01-21
  • 打赏
  • 举报
回复
引用 3 楼 crazy_samba 的回复:
难道你认为malloc/free是线程不安全的。 new/delete/malloc/free都是线程安全的。 引用 楼主 luo6620378xu 的回复:按照我的理解,有可能是线程不安全的。因为有的版本的new和delete是用 malloc和free实现的。
我以前一直认为malloc和free是线程不安全的。

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧