【问题标题】:C++ std::Thread program does nothing [closed]C++ std::Thread 程序什么都不做[关闭]
【发布时间】:2015-05-26 20:28:09
【问题描述】:

我正在使用 std::Thread 类并编写了这个小代码来测试它,但它看起来实际上什么也没做。

#include <iostream>
#include <thread>

using namespace std;

class TestThread
{
  public:
      TestThread();
      ~TestThread();
      void foo();
      void bar();
};

TestThread::TestThread()
{}

TestThread::~TestThread()
{}

void TestThread::foo()
{
  while(true)
    cout << "Thread 1 reporting" << endl;
}

void TestThread::bar()
{
  while(true)
    cout << "Thread 2 reporting" << endl;
}


int main(int argc, char**argv)
{
   TestThread test;
   thread t1(&TestThread::foo, &test);
   thread t2(&TestThread::bar, &test);
   t1.join();
   t2.join();
   return 0;
} 

当我执行这个时,它基本上什么都不做。在我启动它而不打印任何东西后它就停止了。我做错了吗?

【问题讨论】:

  • 不能执行它。它不编译(缺少包含和using namespace)并且不链接(缺少构造函数和析构函数定义)。除此之外,它确实做你想让它做的事情。那么,我们要不要再试一次?
  • 对不起,我没有发布完整的代码,我对 C 或 C++ 并不陌生,我是这个线程的新手,根本不知道我必须使用 -pthread。添加它使事情起作用
  • 我不知道我是否遗漏了什么,但是这段代码编译并逐字成功。
  • 我编辑了它,我没有添加包含和使用命名空间,所以 Lightness 无法编译它。

标签: c++ multithreading


【解决方案1】:

正如 cmets 所说,您缺少 includeusing 语句,因此您可能正在执行其他程序而不是这个程序。

这是一个经过修正的程序,可以实际编译和运行。

#include <thread>
#include <iostream>

using std::thread;
using std::cout;
using std::endl;

class TestThread
{
  public:
    TestThread() { }
    ~TestThread() { }
    void foo();
    void bar();
};

void TestThread::foo()
{
    while(true)
        cout << "Thread 1 reporting" << endl;
}

void TestThread::bar()
{
    while(true)
        cout << "Thread 2 reporting" << endl;
}


int main(int argc, char**argv)
{
    TestThread test;
    thread t1(&TestThread::foo, &test);
    thread t2(&TestThread::bar, &test);
    t1.join();
    t2.join();
    return 0;
}

下面是编译和运行它的方法,假设你把它放在一个名为ThreadPlay.cc的文件中。

g++ -std=c++11 -pthread ThreadPlay.cc
./a.out

【讨论】:

  • 我没有错过包含和语句,我只是复制了代码的相关部分,我认为我在使用线程时出错或需要调用其他方法。但我想我在编译时没有使用-pthread。我用 -pthread 再次尝试了它,它工作了谢谢你
  • @Tychus,当您的问题涉及运行代码并且您发布一个无法编译的示例时,有时社区可能会有点苛刻,因为它增加了解决实际问题所需的工作量(开销) .但是,由于这几乎是你唯一缺少的东西,我认为你已经付出了足够的努力。
  • 没有什么“苛刻”的。您确实错过了包含和语句,并且在添加它们时,您的问题无法重现。所以,你在浪费我们的时间。这不是“苛刻”:这是事实。这就是我们要求您提供testcase 的原因:它证明问题出在您所说的那样。在这种情况下,它不是。不仅仅是我们:学习这项技能类似于学习如何调试,这对你自己的职业生涯至关重要。干杯。
  • @merlin2011:要求人们在 meta 上发帖寻求帮助重新打开愚蠢的、不可重现的问题是不负责任的。我对 25k 用户的期望更高。它不只是“不编译”;即使进行编译,它也不匹配问题。请在评论之前实际尝试一下。
  • @LightnessRacesinOrbit,这很公平。我已经删除了该评论。不包括-pthread 的问题是可以重现的。问题是 OP 未能正确描述实际问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
  • 2017-02-09
  • 2014-10-02
  • 1970-01-01
  • 2022-11-30
  • 2019-01-17
  • 2011-03-24
相关资源
最近更新 更多