c++ - 在 C++ 中优化线程
问题描述
我对附加代码有三个问题,这与线程有关。我需要进行函数调用以提供有关以下三项的信息:
- 线程是否为
vecOfThreads[1]
空且当前没有任何任务在其上运行 - 是线程
vecOfThreads[0]
joinable()
但还没有准备好被join()
编辑 - 这将是 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 个线程可用。我希望在其中一个线程完成时立即提交新任务。这可能吗?
感谢您的时间。
解决方案
推荐阅读
- gitlab - 带有 SAML 的 Gitlab 将页面重定向到 gitlab-root
- tfs - TeamCity 还原 TFS NuGet 提要 401 未经授权
- wordpress - TypeRocket 表单元素
- python - 使用 structlog 登录 Python 项目并记录需要删除的第三方库
- c - 从目录中删除文件 - 类似 ext 的文件系统实现
- outlook - 有没有办法在 Outlook for Mac 中调试函数文件?
- python - 找到 numpy 数组的排列以将其与另一个数组对齐?
- android - 有没有办法将 BottomSheet 转换为 Activity?
- regex - 无法弄清楚如何替换 xml 中的标签
- react-native - 使用条带连接和本机反应