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();
}
相关推荐
NiNi_suanfa2 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
小糖学代码3 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
Data_agent3 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
信奥胡老师3 小时前
苹果电脑(mac系统)安装vscode与配置c++环境,并可以使用万能头文件全流程
c++·ide·vscode·macos·编辑器
妖灵翎幺3 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
风筝在晴天搁浅4 小时前
代码随想录 718.最长重复子数组
算法
kyle~4 小时前
算法---回溯算法
算法
Halo_tjn4 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
star _chen4 小时前
C++实现完美洗牌算法
开发语言·c++·算法
周杰伦fans4 小时前
pycharm之gitignore设置
开发语言·python·pycharm