c++ - 如何处理多个线程的重复启动?

标签 c++ multithreading c++11

直到现在,在使用线程时,我总是在我的程序中立即启动它们,然后让它们等待来自主控制线程的通知。

std::vector<std::thread> threads;
for(int i = 0; i != thread_count; ++i) {
    threads.push_back(std::thread(&MyClass::myfunction, this));
}

/* some time later in the code */
for(auto& t : threads) {
    t.join();
}

现在我想从我的控制线程运行的函数按需启动线程,但我不确定如何处理线程对象及其连接。

下面会在每次调用时将一个新的线程对象推送到 vector 上,这让我觉得不太理想:

std::vector<std::thread> threads;
while(accumulating_data) {
    if(buffer_full) {
        threads.push_back(std::thread(&MyClass::myfunction, this));
    }
}

让 vector 在连续运行的线程上保持不超过最大数量似乎更可取。我也不知道如何在不阻塞控制线程的情况下加入线程。

如果我改为这样做:

// dummy code, in my real code I have a queue of idle IDs
std::vector<std::thread> threads(thread_count);
while(accumulating_data) {
    if(buffer_full) {
        threads[thread_id] = std::thread(&MyClass::myfunction, this);
        if(++thread_id == thread_count) { thread_id = 0; }
    }
}

...我很快就崩溃了,可能是因为我没有加入或正在重新分配给一个已经包含 std::thread 对象的 vector 元素。

关于如何实现按需启动线程而不是让它们等待的目标的任何提示?

更新:

通过引入 std::thread.joinable() 检查,我设法让代码在不崩溃的情况下运行。我仍然对如何更优雅地处理这个问题持开放态度,所以我不会让它成为我自己问题的答案:

std::vector<std::thread> threads(thread_count);
while(accumulating_data) {
    if(buffer_full) {
        if(threads[thread_id].joinable()) {
            threads[thread_id].join(); }
        }
        threads[thread_id] = std::thread(&MyClass::myfunction, this);
        if(++thread_id == thread_count) { thread_id = 0; }
    }
}

最佳答案

通过引入 std::thread.joinable() 检查,我设法让代码在不崩溃的情况下运行。我仍然对如何更优雅地处理这个问题持开放态度:)

std::vector<std::thread> threads(thread_count);
while(accumulating_data) {
    if(buffer_full) {
        /* the following check returns false prior to an assignment */
        if(threads[thread_id].joinable()) {
            threads[thread_id].join(); }
        }
        threads[thread_id] = std::thread(&MyClass::myfunction, this);
        if(++thread_id == thread_count) { thread_id = 0; }
    }
}

关于c++ - 如何处理多个线程的重复启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738971/

相关文章:

C++11 char16_t strstr 和 sprintf 等效

c++ - 如何使用对对象的引用来初始化 boost::any?

c++ - 使用结构体初始化 OpenGL VBO

c++ - 如何获取系统的IP地址

c++ - 函数调用中字符串的变量名,C++

java - 为什么ExecutorService接口(interface)没有实现AutoCloseable?

c++ - 使用动态数组初始化分配给其索引的默认值是什么?

multithreading - 在 Grails 服务中管理线程

c++ - 三十部分库中的线程安全

c++ - 线程工作目录