Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Synchro#3
// Имеется объект (TaskPool), владеющий несколькими постоянно действующими рабочими потоками (WorkingThread). // Объект получает на вход задачу, представленную в виде функтора (TaskFunctor), устанавливает ее в контекст рабочих потоков, // освобождает их и ожидает завершения вычислений (рабочие потоки засыпают). // Представить схему синхронизации для изложенной ситуации #include <iostream> #include <boost/thread.hpp> #include <boost/scoped_ptr.hpp> class TaskFunctor { public: virtual void Arrange(int thread_total_num) = 0; virtual void Execute(int thread_num) = 0; virtual void Finish() = 0; }; struct TaskPool; class WorkingThread { TaskPool* pool; int thread_num; public: WorkingThread(TaskPool* p, int thread_num_) : pool(p), thread_num(thread_num_) {} void operator()() { // ... <---- } }; class TaskPool { boost::thread_group performer_threads; boost::scoped_ptr<TaskFunctor> problem; // .... <---- public: TaskPool(int working_thread_num) { // ... <---- for (int i = 0; i < n; ++i) performer_threads.create_thread(WorkingThread(this, i)); } ~TaskPool() { // ... <---- } bool Execute(TaskFunctor& f){ // ... <---- return false; } }; // ----------------------------------- template<class ArgType> class MyJob : public TaskFunctor { std::vector<ArgType> data; std::function<ArgType(int)> fun; int thread_total_num; int block_size; public: template<typename Functor> MyJob(int size, Functor f) : data(size, 0), fun(f){} void Arrange(int thread_total_num_){ thread_total_num = std::min((int)data.size(), thread_total_num_); block_size = data.size() / thread_total_num; } void Execute(int thread_num) { if(thread_num >= thread_total_num) return; auto region = std::make_pair(0, data.size()); if (thread_num) { region.first += block_size * thread_num; } if (thread_num != thread_total_num - 1) { region.second = region.first + block_size; } for(int n = region.first; n != region.second; ++n) { data[n] = fun(n); } } void Finish(){} }; int main() { TaskPool pool(8); MyJob<int> job(10000000, [](int x){return 1; }); pool.Execute(job); return 0; }
run
|
edit
|
history
|
help
0
Weighted Average
MoaJhalMury
sin_approximation
Sum of digits of number
Procesos E
How to access member function of a class using scope
MemCpySetChar
Best way for getting more precision no.
PointPattern
Reverese every K node in list