【发布时间】:2015-08-04 18:14:35
【问题描述】:
我正在研究实现一个 FIFO 线程队列,其中创建了线程 lambda,但一次只处理 X 个线程。
我假设线程将捕获一些局部变量,但没有别的。
我正在尝试做的一个最小示例是:
#include <stdio.h>
#include <mutex>
#include <thread>
#include <atomic>
#include <vector>
#include <algorithm>
#include <condition_variable>
int main()
{
std::vector<std::thread> threads;
std::condition_variable condition;
std::mutex mutex;
std::atomic<unsigned int> thread_count( 0 );
for ( int i = 0; i < 20; i++ )
{
std::unique_lock<std::mutex> lock ( mutex );
condition.wait( lock, [&]{ return thread_count < 8;} );
std::thread t = std::thread([&,i]()
{
printf ("I am Thread #: %d with current thread count: %u\n", i, unsigned( thread_count ) );
thread_count--;
});
threads.push_back( std::move( t ) );
thread_count++;
}
for ( auto & t : threads ) t.join();
return 0;
}
我想在那个 for 循环中创建线程对象/lamdas,然后让它们最多运行 8 个线程。
当前输出为:
I am Thread #: 0 with current thread count: 3
I am Thread #: 3 with current thread count: 4
I am Thread #: 2 with current thread count: 4
I am Thread #: 5 with current thread count: 3
I am Thread #: 1 with current thread count: 3
I am Thread #: 4 with current thread count: 5
I am Thread #: 6 with current thread count: 1
I am Thread #: 7 with current thread count: 1
I am Thread #: 8 with current thread count: 1
I am Thread #: 9 with current thread count: 1
I am Thread #: 10 with current thread count: 1
I am Thread #: 11 with current thread count: 1
I am Thread #: 12 with current thread count: 1
I am Thread #: 13 with current thread count: 1
I am Thread #: 14 with current thread count: 1
I am Thread #: 15 with current thread count: 1
I am Thread #: 16 with current thread count: 1
I am Thread #: 17 with current thread count: 1
I am Thread #: 18 with current thread count: 1
I am Thread #: 19 with current thread count: 1
这显然永远不会达到 8 个线程的最大数量。
您可以亲自查看here
【问题讨论】:
-
不清楚你在问什么,你的代码示例与这个问题有什么关系。这也读得太多了 gimmetehcodez
-
恭喜你实现了对这段代码的渴望。继续一个实际的问题..
-
您没有尝试自己实现它。你只是要求别人为你做这件事。您的答案可以在 C++ Concurrency in Action Practical Multithreading, Anthony Williams, 2012, §9.1 中找到。
-
@bky_drytt 你是什么意思我没有尝试自己实现它?上面的代码是我在收到 Puppy 和 Barry 的批评后写的。我不是要求任何人用勺子喂我,而只是帮助编写这样的循环/机制/模式。我的印象是这就是 SO 的用途。任何链接或其他提示就足够了。
-
你是对的。我对指控感到抱歉。您应该查看我在之前评论中指向您的书的部分,因为它正是您需要的。
标签: c++ multithreading c++11 gcc threadpool