C ++从多个线程访问向量 [英] C++ Access to vector from multiple threads

查看:94
本文介绍了C ++从多个线程访问向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,一些线程正在运行.每个线程都获得一个指向某个对象的指针(在我的程序中为vector).然后每个线程都会修改向量.

In my program I've some threads running. Each thread gets a pointer to some object (in my program - vector). And each thread modifies the vector.

有时我的程序会因段错误而失败.我以为是因为线程A开始对向量做一些操作而线程B还没有完成对它的操作?会不会是真的?

And sometimes my program fails with a segm-fault. I thought it occurred because thread A begins doing something with the vector while thread B hasn't finished operating with it? Can it bee true?

我应该如何解决?线程同步?还是制作一个标志VectorIsInUse并在操作它时将该标志设置为true?

How am I supposed to fix it? Thread synchronization? Or maybe make a flag VectorIsInUse and set this flag to true while operating with it?

推荐答案

vector也不是线程安全的.您必须自己明确管理同步. std::mutex

vector, like all STL containers, is not thread-safe. You have to explicitly manage the synchronization yourself. A std::mutex or boost::mutex could be use to synchronize access to the vector.

请勿使用标志,因为它不是线程安全的:

Do not use a flag as this is not thread-safe:

  • 线程A检查isInUse标志的值,它是false
  • 线程A被挂起
  • 线程B检查isInUse标志的值,它是false
  • 线程B将isInUse设置为true
  • 线程B被暂停
  • 线程A已恢复
  • 线程A仍然认为isInUsefalse并将其设置为true
  • 线程A和线程B现在都可以访问vector
  • Thread A checks value of isInUse flag and it is false
  • Thread A is suspended
  • Thread B checks value of isInUse flag and it is false
  • Thread B sets isInUse to true
  • Thread B is suspended
  • Thread A is resumed
  • Thread A still thinks isInUse is false and sets it true
  • Thread A and Thread B now both have access to the vector

请注意,每个线程都必须在使用整个时间期间锁定vector.这包括修改vector并使用vector的迭代器,因为如果迭代器所引用的元素为erase()vector进行内部重新分配,则迭代器可能变得无效.例如,不要:

Note that each thread will have to lock the vector for the entire time it needs to use it. This includes modifying the vector and using the vector's iterators as iterators can become invalidated if the element they refer to is erase() or the vector undergoes an internal reallocation. For example do not:

mtx.lock();
std::vector<std::string>::iterator i = the_vector.begin();
mtx.unlock();

// 'i' can become invalid if the `vector` is modified.

这篇关于C ++从多个线程访问向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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