I have executed below program where I have created 100 threads to execute concurrently. Please note this is a sample program made. I understand multiple threads are not required for below program but my intention was to test mutex.
class ThreadPool{
public:
ThreadPool(int num = 10);
~ThreadPool();
void AssignPool();
void doSometask();
void inc();
private:
boost::asio::io_service ioService;
boost::thread_group threadpool;
boost::asio::io_service::work * work;
volatile int p_size;
int pool_sz;
boost::mutex io_mutex;// with boost lock
};
void ThreadPool::AssignPool()
{
std::cout<<std::endl<<"pool_sz="<<pool_sz<<std::endl;
for(int i=0;i<pool_sz;i++)
{
ioService.post(boost::bind(&ThreadPool::doSometask, this));
}
}
void ThreadPool::inc()
{
p_size++;
}
void ThreadPool::doSometask()
{
// boost::mutex::scoped_lock lock(io_mutex);
for(int i=0;i<10000;i++){
inc();
}
}
ThreadPool::ThreadPool(int num):p_size(0)
{
pool_sz = num;
work = new boost::asio::io_service::work(ioService);
for(int i =0;i<num;i++)
{
threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService )) ;
}
}
ThreadPool::~ThreadPool()
{
delete work;
ioService.stop();
threadpool.join_all();
}
int main()
{
ThreadPool p1(100);
p1.AssignPool();
}
Case 1: Above program was executed by commenting "boost::mutex::scoped_lock lock(io_mutex);" line which is "no mutex case". time taken by the program was
real 0m1.386s
user 0m0.483s
sys 0m9.937s
Case 2: With Mutex: However when I run this program with mutex i.e. "boost::mutex::scoped_lock lock(io_mutex);" line. This program is taking lesser time.
real 0m0.289s
user 0m0.067s
sys 0m0.230s
In my understanding with mutex, program should have taken much more time than without mutex. What went wrong here??