, " " , , , . , , , doSometask()
, .
doSometask
, , , :
#include <iostream>
#include <chrono>
#include <atomic>
#include <boost/asio/io_service.hpp>
#include <boost/thread.hpp>
class ThreadPool
{
public:
ThreadPool(int num = 10, int cycles = 10000);
~ThreadPool();
void inc(volatile int* x);
void AssignPool();
void doSometask(volatile int* x);
void AssignPoolSync();
void doSometaskSync(volatile int* x);
private:
boost::asio::io_service ioService;
boost::thread_group threadpool;
boost::asio::io_service::work * work;
std::atomic<int> p_size;
int *xsize;
int pool_sz, cycles;
boost::mutex io_mutex;
};
void ThreadPool::AssignPool()
{
for (int i = 0; i<pool_sz; ++i)
ioService.post(boost::bind(&ThreadPool::doSometask, this, &xsize[i]));
}
void ThreadPool::AssignPoolSync()
{
for (int i=0; i<pool_sz; ++i)
ioService.post(boost::bind(&ThreadPool::doSometaskSync, this, &xsize[i]));
}
void ThreadPool::inc(volatile int* x)
{
*x = *x + 1;
}
void ThreadPool::doSometask(volatile int* x)
{
for (int i=0; i<cycles; ++i)
{
inc(x);
if (i & 255 == 0)
p_size++;
}
}
void ThreadPool::doSometaskSync(volatile int* x)
{
boost::mutex::scoped_lock lock(io_mutex);
doSometask(x);
}
ThreadPool::ThreadPool(int num, int cycles)
{
pool_sz = num;
p_size = 0;
this->cycles = cycles;
xsize = new int[num];
memset(xsize, 0, num * sizeof(int));
work = new boost::asio::io_service::work(ioService);
for (int i=0; i<pool_sz; ++i)
threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
}
ThreadPool::~ThreadPool()
{
delete work;
ioService.stop();
threadpool.join_all();
delete[] xsize;
}
int main(int argc, const char** argv)
{
const int C = argc>1 ? std::stoi(argv[1]) : 10000;
const int T = argc>2 ? std::stoi(argv[2]) : 100;
const int N = argc>3 ? std::stoi(argv[3]) : 50;
long long t_min[2] = {0};
for (int i = 0; i<N*2; ++i)
{
auto t0 = std::chrono::high_resolution_clock::now();
{
Sleep(1);
ThreadPool pool(T, C);
if (i&1)
pool.AssignPoolSync();
else
pool.AssignPool();
}
auto t1 = std::chrono::high_resolution_clock::now();
t_min[i&1] = std::min(i>1 ? t_min[i&1] : (t1-t0).count(), (t1-t0).count());
}
printf("timeSync / time: %f\n", (t_min[1] + 0.0) / (t_min[0] + 0.0));
}
, : , , , . , , , .
, 4- :
test> test.exe 10000 100
timeSync / time: 1.027782
test> test.exe 500000 100
timeSync / time: 3.531433
, 10000 , , , 500000, 3,5