c++ - for循环中的多线程错误

标签 c++ multithreading

我正在尝试使用线程添加一个简单的 for 循环,但仍然无法解决问题。我检查了很多原因,但找不到任何解决方案。

我有一个简单的类,它有两个方法 A()B()。在另一个类中,我正在调用方法 A()。这是它的样子:

void MyClass::A()
{
    std::vector<std::thread> threads;
    for(int i=0;i<2;i++)
    {
        threads.push_back(std::thread(&MyClass::B, this));
    }
    for(auto &t : threads)
    {
        if(t.joinable())
            t.join();
    }
}

void MyClass::B()
{
}

但我仍然收到一些错误:

#0 ??   ?? () (??:??)
#1 00446D62 pthread_create_wrapper () (??:??)
#2 75327FB0 msvcrt!_cexit() (C:\Windows\SysWOW64\msvcrt.dll:??)
#3 040C8710 ?? () (??:??)
#4 753280F5 msvcrt!_beginthreadex() (C:\Windows\SysWOW64\msvcrt.dll:??)
#5 75B17C04 KERNEL32!BaseThreadInitThunk() (C:\Windows\SysWOW64\kernel32.dll:??)
#6 77ABAB8F ?? () (??:??)
#7 77ABAB5A ?? () (??:??)
#8 ??   ?? () (??:??)

有人知道哪里出了问题吗?

再补充一点。这:

void MyClass::A()
{
    std::thread t(&MyClass::B, this);
    if(t.joinable())
        t.join();
}

void MyClass::B()
{
}

工作没有任何问题。

最佳答案

我建议使用 new 和指针而不是引用。

虽然引用很好,但评论的数量说明了在这种情况下造成的困惑。您如何证明第三方库实现(例如 std)将按照您期望的方式工作?跨平台?

如果您使用:

std::vector<std::thread *> threads;

和:

threads.push_back(new std::thread(&MyClass::B(), this));

当然,当您完成线程时使用“删除”,困惑就会消除。

此外,该代码正在将“A”类的相同实例加载到所有线程的数组中。如果您在函数“B”中使用 A 中的成员变量,而没有任何类型的多线程保护(例如信号量、关键部分等),您的代码将永远无法正常工作。使用“new”创建线程实例可以避免复制构造函数或赋值运算符对 vector 类造成的问题。

#include <SDKDDKVer.h>
#include <vector>
#include <thread>
#include <iostream>

using namespace std;

class MyClass {
  public:
    void A() {
      cout << "starting\n";
      cout << "creating threads\n";
      vector<thread*> threads;
      for (int i = 0;i<4;i++) {
        thread * t = new thread(&MyClass::B, this);
        cout << "creating thread "<<t<<" id:"<<t->get_id()<<"\n";
        threads.push_back(t);
      }
      cout << "waiting for threads to complete\n";
      for (thread * t : threads) {
        if (t->joinable()) {
          t->join();
        }
        cout << "destroying "<<t<<"\n";
        delete t;
      }
      cout << "done\n";
   }

   void B() {
     // now it would be very bad if this function used 
     // member variables that are part of this instance of A
     cout << "hello from " << this << "\n";
   }
}; 

int main() {
  MyClass cls;
  cls.A();
  return 0;
}

关于c++ - for循环中的多线程错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35632086/

相关文章:

java - 如果我在实例方法中放置静态锁会发生什么?

c++ - 如何使用 CSingleLock 提供对此缓冲区的访问权限?

c++ - 在另一个线程中注入(inject) C++ 异常

C++ 对象工厂函数

c++ - 从未调用过 Win32 ListBox WNDPROC

c++ - 如何查找与包含相关的问题 - 可视化包含树

c++ - 没有匹配函数调用 sscanf

c# - 多路复用流? (同时读/写)

C# + WinRT + 用于网络(Azure 移动服务)操作的 Monogame 线程

c++ - gdb 显示类成员的乱码值,尽管代码有效