Re: Why is java consumer/producer so much faster than C++
In article <jumg3b$nvn$1@news.albasani.net>, Melzzzzz <mel@zzzzz.com> wrote:
On Tue, 24 Jul 2012 12:51:20 +0000 (UTC)
yatremblay@bel1lin202.(none) (Yannick Tremblay) wrote:
In article <86c79114-84e6-4065-a9a4-b5b3edf8fcac@googlegroups.com>,
Howard Hinnant <howard.hinnant@gmail.com> wrote:
I made a few changes to your code:
1. I only signal if the capacity becomes non-zero or non-full.
2. If the queue is the queue has got some items in it and the mutex
is locked, the put thread yields to the take thread. If the queue
has some free space in it and the mutex is locked, the take thread
yields to the put thread.
Are you sure about the usefulness of #2?
Problem is that we need to reduce waiting on condition to minimum
as more condition waits program is slower.
Ideally there would be no condition waits (maximum speed).
OK, for this test program, I guess it might make sense (albeit in my
case, this worsens the results)
However, you should be careful to generalizing this to a "real"
program. This test program passes integers back and forth via the
queue and do no "work" at all. A "real" program will most likely do
work.
Typically for a real program, fcons/fprod will look more like:
void fprod()
{
for(;;)
{
Job job = CreateJob();
queue.put(job);
}
}
void fcons()
{
for(;;)
{
Job job = queue.take();
ProcessJob(Job);
}
}
And the cost of ProcessJob()/CreateJob() will dwarf the cost of
put()/take() by several order of magnitude. (in your test program, the
cost of storing the integer is dwarfed by the cost of accessing the
queue)
For such a system, you actually want it to be a common occurence that
the consumer blocks waiting on a condition.
Doing a few tests myself, adding this in m queue seems to reduce
performance by some 20%: while (!lock.owns_lock())
{
if (queue_.size() > capacity_/4)
{
for (int i = 0; i < 3250; ++i)
std::this_thread::yield();
lock.try_lock();
}
else
{
lock.lock();
break;
}
}
This is second version, on my system first version seems better
for smaller capacities...