在我的程序中,我想运行两个单独的线程,它们是初始化并在主线程中启动。这个概念对我来说很好,但是当我现在必须在其中一个子线程上进行冷却而它没有暂停时,它似乎仍然暂停线程;
将此视为一个例子:
#include <iostream>
#include <thread>
class testClass {
static void grandchild();
static void child();
public:
void parent();
};
void testClass::grandchild() {
//infinite loop of nothing;
while (true);
}
void testClass::child() {
//thread initalising and
std::thread grand(&testClass::grandchild);
std::cout << "before join" << std::endl;
grand.join();
std::cout << "after join" << std::endl;
}
void testClass::parent() {
std::thread child(&testClass::child);
child.join();
}
int main() {
testClass parentclass;
parentclass.parent();
}
此程序的输出现在是
当我执行this_thread :: sleep_for和其他暂停线程的函数时,也会发生这种情况。任何人都可以解释为什么会发生这种情况,以及我可以正确地实现这一点,或者如果在C ++中甚至可以实现这一点?
答案 0 :(得分:3)
.join()
表示&#34;等到该线程完成&#34;。 parent
等待child
,child
等待grandchild
,grandchild
陷入无限循环,因此没有任何反应。您实际上正在运行单线程,因为您与生成的线程一起加入。
您迫不及待地使用.detach()
而不是.join()
,但是您应该在从main
返回之前加入所有主题。
答案 1 :(得分:2)
此程序运行正常。
在加入&#34;。
然后等待无限while(1)
循环结束。
在无限时间后,它会在加入&#34;后显示&#34;
如果你打算采取不同的行为,也许你可以解释一下这种不同的行为。
答案 2 :(得分:2)
这是一个修改过的程序,它使用孙子线程在更改值之前等待3秒。
子线程一直在运行。
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
class testClass {
public:
void grandchild();
void child();
void parent();
std::atomic<int> value{0};
};
void testClass::grandchild()
{
std::this_thread::sleep_for(std::chrono::seconds(3));
value = 5;
}
void testClass::child()
{
//thread initalising and
std::cout << "Starting grandchild thread.\n";
std::thread grand(&testClass::grandchild,this);
//grand.detach(); // could detach so that a join() will not be required later
for (int x{0}; x<5; ++x) {
std::cout << x << '\t' << value << '\n';
std::this_thread::sleep_for(std::chrono::seconds(1));
}
grand.join();
}
void testClass::parent()
{
std::cout << "Starting child thread.\n";
std::thread child(&testClass::child, this);
child.join();
}
int main()
{
std::cout << "Starting program\n";
std::cout << "Starting parent thread.\n";
testClass parentclass;
parentclass.parent();
}
输出:
Starting program
Starting parent thread.
Starting child thread.
Starting grandchild thread.
0 0
1 0
2 0
3 5
4 5