【问题标题】:C++ Multithreading methods in an object with infinite loops具有无限循环的对象中的 C++ 多线程方法
【发布时间】:2021-11-23 08:54:58
【问题描述】:

我以前从未做过任何 C++ 或多线程,需要帮助。

假设我的 hpp 文件中有这个。

Class Test{
  public:
  struct type_something_to_kill_the_foo_thread something_to_kill_the_foo_thread;// I don't know what
  void foo(stuff stuff){
    while(true) does_stuff(stuff);
  }
  void thread_foo(stuff stuff){
  std::thread th = (&Test::foo, this, stuff);
  something_to_kill_the_foo_thread = th; // or th.getid() any mechanism so that I can invoke a function to destroy the thread
  sleep(MAX_INT);
  }
}

我主要有这个。

Test t = Test();
t.thread_foo("random stuff1");
t.thread_foo("random stuff2");
...

如何在不使用主线程的情况下并行化这两个调用,以便我的主线程继续运行?如果需要,我应该将 join() 放在哪里以及如何销毁第一个线程?

我一直在学习在线教程,因为他们总是在 main() 中调用 std::thread。

【问题讨论】:

  • 有很多例子,即使在 cppreference.com 上也是如此。从thread_foo返回std::thread,最后调用std::thread::join()。
  • 要终止线程,您可能需要std::atomic_flag。线程定期检查标志,如果设置则退出。另一个线程设置标志(可能是joins)。您不想要终止正在运行的线程。它会破坏整个程序的稳定性。 C++ 标准出于非常充分的理由留下了一种线程终止方法。

标签: c++ multithreading


【解决方案1】:

这就是你制作线程的方式:

#include <thread>

int main() {
  Test t = Test();

  std::thread(t.thread_foo, "random stuff1").detach()
  std::thread(t.thread_foo, "random stuff2").detach()
  // Works in parallel
}

【讨论】:

    猜你喜欢
    • 2020-12-25
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    相关资源
    最近更新 更多