std string与线程安全,是C ++ std :: set线程安全吗?

I've a question about the thread safety of std::set.

As far as I know I can iterate over a set and add/erase members and that doesn't invalidate the iterators.

But consider following scenario:

thread 'A' iterates over a set of shared_ptr

thread 'B' occasionally adds items to this set.

I've experienced segfaults as the program runs and I'm not sure why this happens. Is lack of thread safety the cause?

解决方案

STL has no built in thread support, so you'll have to extend the STL

code with your own synchronization mechanisms to use STL in

a multithreaded environment.

For example look here: link text

Since set is a container class MSDN has following to say about the thread safety of the containers.

A single object is thread safe for reading from multiple threads. For example, given an object A, it is safe to read A from thread 1 and from thread 2 simultaneously.

If a single object is being written to by one thread, then all reads and writes to that object on the same or other threads must be protected. For example, given an object A, if thread 1 is writing to A, then thread 2 must be prevented from reading from or writing to A.

It is safe to read and write to one instance of a type even if another thread is reading or writing to a different instance of the same type. For example, given objects A and B of the same type, it is safe if A is being written in thread 1 and B is being read in thread 2.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值