线程池C++

Jus*_*ASK 7 c++ multithreading

我有以下for循环:

for (int i = 0; i < 100; i++) {
    someJob();
}
Run Code Online (Sandbox Code Playgroud)

我想只用5个线程运行这个函数,我该怎么办?

我尝试的是使用5个线程创建数组,如果索引等于5以等待所有线程再次使用它,但我确信还有另一种方法可以做到这一点:

std::thread t[THREAD_COUNT];
int j=0;

 for (int i = 0; i < 100; i++) {
    t[j++] = std::thread(someJob);
    if (j == THREAD_COUNT)
    {
        for (int k = 0; k < THREAD_COUNT; k++)
        {
            if (t[k].joinable())
                t[k].join();
        }
        j = 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么建议吗?(我不能用boost)

谢谢!

Gal*_*lik 1

您可以创建一个函数来测试您的线程数组,以找到一个空闲线程来运行每个连续的作业。像这样的东西:

// synchronized output to prevent interleaving of results
#define sync_out(m) do{std::ostringstream o; o << m << '\n'; std::cout << o.str();}while(0)

void someJob(int id)
{
    sync_out("thread: " << id);
}

template<typename Job>
void start_thread(std::vector<std::thread>& threads, Job&& job)
{
    // find an ended thread
    for(auto&& thread: threads)
    {
        if(thread.joinable()) // still running or waiting to join
            continue;

        thread = std::thread(job);
        return;
    }

    // if not wait for one
    for(auto&& thread: threads)
    {
        if(!thread.joinable()) // dead thread (not run or already joined)
            continue;

        thread.join();
        thread = std::thread(job);
        return;
    }
}

int main()
{

    std::vector<std::thread> threads(5); // 5 threads

    for(int i = 0; i < 100; i++)
        start_thread(threads, [=]{someJob(i);});

    // wait for any unfinished threads    
    for(auto&& thread: threads)
        if(thread.joinable())
            thread.join();
}
Run Code Online (Sandbox Code Playgroud)