首页 > 解决方案 > 在 C++ 中优化线程

问题描述

我对附加代码有三个问题,这与线程有关。我需要进行函数调用以提供有关以下三项的信息:

  1. 线程是否为vecOfThreads[1]空且当前没有任何任务在其上运行
  2. 是线程vecOfThreads[0] joinable()但还没有准备好被join()编辑
  3. 这将是 2) 的 else 语句。如果一个线程是joinable()并且不会等待join()然后继续join()
#include <iostream>
#include <chrono> // std::chrono::microseconds
#include <thread> // std::this_thread::sleep_for
#include <vector>

void f1();

void f1() {
    std::this_thread::sleep_for(std::chrono::seconds {3});
    std::cout << "DONE SLEEPING!" << std::endl;
}

int main() {
    int processor_count = 2;  // consider that this CPU has two processors
    std::vector<std::thread> vecOfThreads(processor_count);

    std::thread t1(f1);
    vecOfThreads[0] = std::move(t1);

    if (vecOfThreads[0].joinable()) {  // how to check to see if vecOfThreads[1] would be good to start a process on?
        std::cout << "this is joinable, but not yet ready to be joined \n";
        std::cout << "How to know: \n \t 1) if the thread is not being used "
                     "\n \t 2) if the thread is in use, but not yet ready to be `join()`ed \n \t "
                     "3) if the thread is both joinable and will not wait for a join()" << std::endl;
        vecOfThreads[0].join();
    }

    return 0;
}

编译

g++ -std=c++17 -pthread

我希望能够提交 12 个任务,但我只有 2 个线程可用。我希望在其中一个线程完成时立即提交新任务。这可能吗?

感谢您的时间。

标签: c++multithreading

解决方案


推荐阅读