C++多线程【线程管控】之线程转移以及线程数量和ID

1. 移交线程归属权

std::thread支持移动语义,对于一个具体的执行线程,其归属权可以在几个std::thread实例间转移。如下所示

cpp 复制代码
  void some_function();
  void some_other_function();
  std::thread t1(some_function);
  std::thread t2 = std::move(t1);  // move thread ownership

  t1 = std::thread(some_other_function);  // assign new thread to t1

  std::thread t3;
  t3 = std::move(t2);
  t1 = std::move(t3);  // 会终止t1原来执行的线程

其中需要注意的是:

t1 = std::move(t3)操作:在转移之时,t1已经关联运行some_other_function()的线程,因此std::terminate()会被调用,终止整个程序。

也可以从函数内部返回std::thread对象以及把std::thread当做函数参数转移到函数内部,如下所示:

cpp 复制代码
std::thread f() {
  void some_function();
  return std::thread(some_function);
}

std::thread g() {
  void some_other_function(int);
  std::thread t(some_other_function, 42);
  return t;  // 返回线程对象,触发移动构造函数
}

把线程当做行数参数转移到函数内部

cpp 复制代码
// 也可以传递线程对象作为参数
void f(std::thread t);

void some_Function();
std::thread t(some_Function);
f(std::move(t));  // 传递线程对象,触发移动构造

可以把线程当做参数,给类的构造使用,即将类封装到class中。如下:

cpp 复制代码
class scoped_thread {
  std::thread t;

 public:
  explicit scoped_thread(std::thread t_) : t(std::move(t_)) {
    if (!t.joinable()) {
      throw std::logic_error("No thread");
    }
  }

  ~scoped_thread() { t.join(); }

  scoped_thread(scoped_thread const&) = delete;
  scoped_thread& operator=(scoped_thread const&) = delete;
};

// 使用方式如下
void some_other_function(int);
scoped_thread st(std::thread(some_other_function, 42));

生成多个线程,并且等待它们完成运行

cpp 复制代码
void do_work(unsigned id);
void f() {
  std::vector<std::thread> threads;
  for (unsigned i = 0; i < 20; ++i) {
    threads.emplace_back(do_work, i);
  }

  for (auto& entry : threads) {
    entry.join();
  }
}

2.在运行时选择线程数量

借用c+=标准库的std::thread::hardware_concurrency()函数

需要注意的是,硬件支持的线程数量有限,运行的线程数量不应该超出限度(超出的情况称为线程过饱和),因为线程越多,上下文切换越频繁,导致性能降低。

cpp 复制代码
// 并行版的std::accumulate()的简单实现
template <typename Iterator, typename T>
struct accumulate_block {
  void operator()(Iterator first, Iterator last, T& result) {
    result = std::accumulate(first, last, result);
  }
};

template <typename Iterator, typename T>
T parallel_accumulate(Iterator first, Iterator last, T init) {
  unsigned long const length = std::distance(first, last);
  if (!length) return init;

  unsigned long const min_per_thread = 25;
  unsigned long const max_threads =
      (length + min_per_thread - 1) / min_per_thread;

  unsigned long const hardware_threads = std::thread::hardware_concurrency();
  unsigned long const num_threads =
      std::min(hardware_threads != 0 ? hardware_threads : 2, max_threads);

  std::vector<T> results(num_threads);
  std::vector<std::thread> threads(num_threads - 1);

  Iterator block_start = first;
  for (unsigned long i = 0; i < (num_threads - 1); ++i) {
    Iterator block_end = block_start;
    std::advance(block_end, length / num_threads);
    threads[i] = std::thread(accumulate_block<Iterator, T>(), block_start,
                             block_end, std::ref(results[i]));
    block_start = block_end;
  }

  accumulate_block<Iterator, T>()(block_start, last, results[num_threads - 1]);
  for (auto& entry : threads) {
    entry.join();
  }
  return std::accumulate(results.begin(), results.end(), init);
}

3.识别线程

线程ID可以通过std::thread::id获取

当前线程I可以通过std::this_thread::get_id()获取

cpp 复制代码
std::thread::id master_thread;
void some_core_part_of_algorithm() {
  if (std::this_thread::get_id() == master_thread) {
    do_master_thread_work();
  }
  do_common_work();
}
相关推荐
长安er13 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
元亓亓亓14 小时前
LeetCode热题100--62. 不同路径--中等
算法·leetcode·职场和发展
在屏幕前出油14 小时前
二、Python面向对象编程基础——理解self
开发语言·python
小白菜又菜14 小时前
Leetcode 1925. Count Square Sum Triples
算法·leetcode
粉红色回忆14 小时前
用链表实现了简单版本的malloc/free函数
数据结构·c++
阿方索14 小时前
python文件与数据格式化
开发语言·python
登山人在路上15 小时前
Nginx三种会话保持算法对比
算法·哈希算法·散列表
写代码的小球15 小时前
C++计算器(学生版)
c++·算法
AI科技星15 小时前
张祥前统一场论宇宙大统一方程的求导验证
服务器·人工智能·科技·线性代数·算法·生活
k***921615 小时前
【C++】继承和多态扩展学习
java·c++·学习