Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <functional>
- #include <mutex>
- #include <queue>
- #include <vector>
- #include <atomic>
- #include <string>
- #include <chrono>
- #include <cmath>
- using namespace std;
- template <typename T>
- class ThreadsafeQueue {
- mutable mutex mut;
- queue<T> data_queue;
- public:
- ThreadsafeQueue() {};
- void push(T value)
- {
- mut.lock();
- data_queue.push(value);
- mut.unlock();
- }
- bool try_pop(T& value)
- {
- mut.lock();
- if (data_queue.empty()) {
- mut.unlock();
- return false;
- }
- value = data_queue.front();
- data_queue.pop();
- mut.unlock();
- return true;
- }
- bool empty() const
- {
- mut.lock();
- bool is_empty = data_queue.empty();
- mut.unlock();
- return is_empty;
- }
- };
- class ThreadPool {
- atomic_bool done;
- ThreadsafeQueue <function<void()>> tasks_queue;
- unsigned int threads_num;
- vector<thread> threads;
- void thread_worker()
- {
- while (!done) {
- function<void()> task;
- if (tasks_queue.try_pop(task))
- task();
- else
- this_thread::yield();
- }
- }
- public:
- ThreadPool(unsigned int num): done(false)
- {
- threads_num = num;
- cout << "threads_num = " << threads_num << endl;
- try
- {
- for (unsigned int i = 0; i < threads_num; i++) {
- cout << "Thread в„– " << i << endl;
- threads.push_back(thread(&ThreadPool::thread_worker, this));
- }
- }
- catch(...)
- {
- done = true;
- throw;
- }
- }
- ~ThreadPool()
- {
- done = true;
- for(vector<thread>::iterator it = threads.begin(); it != threads.end(); it++)
- it->join();
- }
- template<class _FN, class... _ARGS>
- void submit(_FN _fn, _ARGS... _args)
- {
- tasks_queue.push(bind(_fn, _args...));
- }
- };
- void factorize(long num)
- {
- // cout is not thread safe, so if strings are messed up, it's Ok
- cout << "factorize: thread #" << this_thread::get_id() << ": ";
- int i = 2;
- while (i <= sqrt(num)) {
- if(num%i == 0) {
- cout << " " << i;
- num = num/i;
- } else i++;
- }
- cout << " " << num << endl;
- }
- int main()
- {
- ThreadPool thread_pool(5);
- for (unsigned int i = 20; i < 25; i++)
- thread_pool.submit(&factorize, i);
- fflush(stdout);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement