【发布时间】: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