【问题标题】:Errors with multithreading in for loopfor循环中的多线程错误
【发布时间】:2016-03-30 03:24:57
【问题描述】:

我正在尝试添加一个带有线程的简单 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()
{
}

没有任何问题。

【问题讨论】:

  • @davmac,OP 没有复制,OP 正在移动。
  • 发布的代码是正确的。你确定这是真实的代码吗?请提供复制粘贴 MCVE。
  • FWIW 使用您的代码和一个简单的 main 函数并适当地包含在 linux 上没有问题的工作。建议您按照 SergeyA 的建议发布完整的 MCVE
  • 为什么人们一直在发明效率很低的轮子?只需从领域专家那里获取现有的 parallel_for 实现,例如在 tbbopenmpppl 中实现的那些。
  • 很抱歉,如果它给人这样的印象。我的意思不是“使用我的”(无论如何它不是“我的”)或吸引任何个人关注。我知道手动线程管理是冗长且低效的,至少出于一个明显的原因,这里有一些库可以更有效地实现这类事情。 @SergeyA

标签: c++ multithreading


【解决方案1】:

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

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

如果你使用:

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

和:

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

当然,当你完成线程时,使用“删除”,然后消除混乱。

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

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-20
    • 2013-11-07
    • 2023-03-03
    • 2013-02-24
    • 1970-01-01
    • 2021-02-23
    • 2011-02-13
    • 1970-01-01
    相关资源
    最近更新 更多