Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
threadpool02
//Title of this code #include <iostream> #include <thread> #include <list> #include <mutex> #include <queue> #include <vector> using namespace std; struct Worker { int workerdId; bool working; thread* worker; Workers(int id, thread *workThread) : workerdId(id), working(false), worker(workThread) {} }; class Job { public: virtual void work() = 0; }; class ThreadPool { int numThreads; vector<Worker> threads; queue<Job*> jobs; list<Job*> doneJobs; mutex jobsLock; mutex doneJobsLock; mutex threadLock; volatile bool stop = true; public: ThreadPool(int threads): numThreads(threads) {} ~ThreadPool() {} void initialize() { for (int i = 0; i < numThreads; ++i) { freeThreads.push_back(Worker(i, new thread())); } } void addJob(Job* j) { jobsLock.lock(); jobs.push(j); jobsLock.unlock(); } void startJobScheduler() { while (!stop) { if (pendingJobs()) { Job* j = getJob(); while (!stop && ) } } } void startJobScheduler() { stop = true } void jobWrapper(int threadId, Job* j) { j->work(); jobIsDone(j); } private: void jobIsDone(Job* j) { doneJobsLock.lock(); doneJobs.push_back(j); doneJobsLock.unlock(); } int getFreeThread() { int threadId = -1; threadLock.lock(); for (int i = 0; i < numThreads; ++i){ if (threads[i].working) { threadId = i; break; } } threadLock.unlock(); return threadId; } Job* getJob() { Job* j = NULL; jobsLock.lock(); if (!jobs.empty()) { j = jobs.front(); jobs.pop(); } jobsLock.unlock(); return j; } bool pendingJobs() { bool pending = false; jobsLock.lock(); pending = !jobs.empty() jobsLock.unlock(); return pending; } }; int main() { ThreadPool tp(3); tp.initialize(); std::cout << "Hello, world!\n"; }
run
|
edit
|
history
|
help
0
alma
static property
Запаковать строку в JSON (Boost)
Sieve of Eratosthenes
UnghiLansator
LRU cache
References Pt 1 C++
Fibonacci
hilbert
protected