c++ - 来自另一个线程的线程中断

标签 c++ multithreading

我正在使用类似的方法创建 9 个线程(所有线程都将处理无限循环)

void printStr();

thread func_thread(printStr);
void printStr() {

    while (true) {
        cout << "1\n";
        this_thread::sleep_for(chrono::seconds(1));
    }

}

我还创建了第 10 个线程来控制它们。我如何从第 10 个开始停止或杀死这 9 个线程中的任何一个?或者请建议另一种机制。

最佳答案

例如,您可以使用原子 bool 值:

#include <thread>
#include <iostream>
#include <vector>
#include <atomic>
using namespace std;

std::atomic<bool> run(true);

void foo()
{
  while(run.load(memory_order_relaxed)) 
  { 
    cout << "foo" << endl;
    this_thread::sleep_for(chrono::seconds(1));
  }
}

int main()
{
  vector<thread> v;
  for(int i = 0; i < 9; ++i)
    v.push_back(std::thread(foo));

  run.store(false, memory_order_relaxed);
  for(auto& th : v)
    th.join();

  return 0;
}

编辑(回应您的评论):您还可以使用受互斥锁保护的互变量。

#include <thread>
#include <iostream>
#include <vector>
#include <mutex>

using namespace std;

void foo(mutex& m, bool& b)
{
  while(1)
  { 
    cout << "foo" << endl;
    this_thread::sleep_for(chrono::seconds(1));

    lock_guard<mutex> l(m);
    if(!b)
      break;
  }
}

void bar(mutex& m, bool& b)
{
  lock_guard<mutex> l(m);
  b = false;
}

int main()
{
  vector<thread> v;
  bool b = true;
  mutex m;

  for(int i = 0; i < 9; ++i)
    v.push_back(thread(foo, ref(m), ref(b)));

  v.push_back(thread(bar, ref(m), ref(b)));

  for(auto& th : v)
    th.join();

  return 0;
}

关于c++ - 来自另一个线程的线程中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23188275/

相关文章:

objective-c - 在 macOS 上的另一个线程中设置线程的名称

python - 与python的线程间通信: Plotting memory-consumption using separate python thread

multithreading - node.js 集群中的子进程间通信选项

c++ - 缩放 QGraphicsScene 以填充整个 QGraphicsView

c++ - std::fstream 错误

c++ - 在 C++ 中,我想创建一个循环,不断检查文件的大小,并在文件大小发生变化时执行某些操作

java - Java中的多线程服务器

c++ - C++11 内存模型是否可以防止内存撕裂和冲突?

c++ - 为什么直接调用字符数组不返回内存地址?

c++ - C++ 中各种数据类型的 sizeof() 解释