# Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2006-10-24 18:42:55

Chris Thomasson wrote:

> How does the original algorithm compare to yours?

I haven't tried it yet. Will do.

> Also, how many reader/writer threads are you using, and how many writes do
> you
> perform on average, 'per-writer-thread', lets say every 3 or 4 seconds?

Various. Here's the test:

#include <boost/bind.hpp>
#include <vector>
#include <iostream>
#include <ctime>

int const N = 1048576;
int const n = 1000; // vector size

rw_mutex mtx;
std::vector<int> v( n );

boost::mutex cmx;

//

{
for( int i = 0; i < N; ++i )
{

int m = v.front();

for( std::vector<int>::const_iterator i = v.begin(), end = v.end();
i != end; ++i )
{
assert( *i == m );
}
}

boost::mutex::scoped_lock lock( cmx );
std::cout << " R" << r;
}

void writer( int w )
{
for( int i = 0; i < N; ++i )
{
rw_mutex::scoped_write_lock lock( mtx );

int m = v.front();

for( std::vector<int>::iterator i = v.begin(), end = v.end(); i !=
end; ++i )
{
++*i;
assert( *i == m + 1 );
}
}

boost::mutex::scoped_lock lock( cmx );
std::cout << " W" << w;
}

void test( int nr, int nw )
{
try
{
std::cout << nr << "R + " << nw << "W:";

std::time_t tm = std::time( 0 );

int i = 0;

for( ; i < nr && i < nw; ++i )
{
group.create_thread( boost::bind( writer, i ) );
}

for( ; i < nr; ++i )
{
}

for( ; i < nw; ++i )
{
group.create_thread( boost::bind( writer, i ) );
}

group.join_all();

std::cout << ": " << std::time( 0 ) - tm << std::endl;
}
catch( std::exception const & x )
{
std::cout << x.what() << std::endl;
}
}

int main()
{
test( 0, 1 );
test( 0, 4 );

test( 1, 0 );
test( 1, 1 );
test( 1, 4 );

test( 2, 0 );
test( 2, 1 );
test( 2, 4 );

test( 4, 0 );
test( 4, 1 );
test( 4, 4 );

test( 16, 0 );
test( 16, 1 );
test( 16, 4 );

test( 64, 0 );
test( 64, 1 );
test( 64, 4 );
}