堆栈上的竞争条件

Sum*_*Jha 2 c++ multithreading mutex

我有简单的类Hello,我试图say_hello在不同的线程上调用成员函数.我创建了两个不同的实现它hellos_in_stackhellos_in_heap.hellos_in_heap按预期工作但是hellos_on_stack在成员变量上有竞争条件_i.如何在堆栈中避免使用它mutex

#include <thread>
#include <iostream>
#include <vector>
#include <mutex>

std::mutex mu;

class Hello
{
  int _i;
public:
  Hello()
  {
      std::lock_guard<std::mutex> lock(mu);
      _i = 0;
  }
  ~Hello(){
  }
  void say_hello()
  {
      std::lock_guard<std::mutex> lock(mu);
      std::cout << "say_hello from thread " << ++_i << " " <<this << " " << std::this_thread::get_id() << std::endl;
  }
};

void hellos_in_stack()
{
    std::vector<std::thread> threads;
    for(int i = 0; i < 4; ++i)
    {
        Hello h;
        threads.push_back(std::thread(&Hello::say_hello, &h));
    }

    for(auto& thread : threads){
        thread.join();
    }
}


void hellos_in_heap()
{
    std::vector<std::thread> threads;
    std::vector<Hello *> hellos;
    Hello *h = nullptr;
    for(int i = 0; i < 4; ++i)
    {
        h = new Hello();
        hellos.push_back(h);
        threads.push_back(std::thread(&Hello::say_hello, h));
    }

    for(auto& thread : threads){
        thread.join();
    }

    for(auto hello : hellos){
        delete hello;
    }
}

int main()
{
    hellos_in_stack();
    hellos_in_heap();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sea*_*ine 5

让我们先描述一下竞争状况......

该行Hello h;正在h主线程的堆栈上构建.一旦for循环继续创建下一个线程,h就会被销毁,另一个Hello被创建 - 可能但不能保证与前一个地址处于同一地址h.

h必须在运行其say_hello方法的线程的生命周期内保持活动状态.

一种解决方案是h在新线程的堆栈上创建.这可以这样做:

std::vector<std::thread> threads;
for (int i = 0; i < 4; ++i)
{
    threads.emplace_back([]() {
        Hello h;
        h.say_hello();
    });
}
Run Code Online (Sandbox Code Playgroud)

如果您仍然需要h可从主线程访问的实例,则另一个选项是将它们存储在容器中.

std::vector<std::thread> threads;
std::list<Hello> hellos;
for (int i = 0; i < 4; ++i)
{
    hellos.emplace_back();
    threads.emplace_back(&Hello::say_hello, &hellos.back());
}
Run Code Online (Sandbox Code Playgroud)

使用容器我们引入了一些更复杂的东西.现在,必须注意确保我们以安全的方式使用容器本身.在这种情况下std::list使用而不是std::vector因为调用emplace_back/ push_backon std::vector会导致它调整其缓冲区的大小.这会破坏Hello运行线程下的实例!


运行示例:https://ideone.com/F7STsf

  • 谢谢肖恩的答案.所以基本上我总是要确保线程中使用的对象在线程完成之前不会被销毁. (3认同)