Created
December 31, 2018 07:16
-
-
Save kanrourou/f719b2b10a079fc34f102aa63867394f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Task | |
{ | |
public: | |
Task(int i) | |
{ | |
id = i; | |
} | |
void virtual run() | |
{ | |
int r = rand() % 3001; | |
this_thread::sleep_for(chrono::milliseconds(r)); | |
} | |
int getId() | |
{ | |
return id; | |
} | |
private: | |
int id; | |
}; | |
class ThreadPool | |
{ | |
public: | |
ThreadPool& operator=(const ThreadPool&) = delete; | |
ThreadPool(const ThreadPool&) = delete; | |
ThreadPool() | |
{ | |
for (int i = 0; i < NUM_OF_THREADS; ++i) | |
{ | |
thread th(bind(&ThreadPool::start, this)); | |
pool.push_back(move(th)); | |
} | |
} | |
void execute(Task& task) | |
{ | |
//crucial part | |
unique_lock<mutex> lock(m); | |
cv.wait(lock, [&] {return q.size() < MAX_CAPACITY; }); | |
cout << "Task " << to_string(task.getId()) << " is added to the blocking queue..." << endl; | |
q.push(move(task)); | |
//notify there is available task | |
cv.notify_one(); | |
} | |
private: | |
queue<Task> q; | |
mutex m; | |
condition_variable cv; | |
const int MAX_CAPACITY = 5; | |
const int NUM_OF_THREADS = 6; | |
vector<thread> pool; | |
void start() | |
{ | |
while (true) | |
{ | |
//crucial part | |
unique_lock<mutex> lock(m); | |
cv.wait(lock, [&] {return q.size(); }); | |
Task&& task = move(q.front()); | |
q.pop(); | |
//notify there is space to add more tasks | |
cout << "Task " << to_string(task.getId()) << " is running..." << endl; | |
cv.notify_one(); | |
lock.unlock(); | |
//perform task | |
task.run(); | |
} | |
} | |
}; | |
void testThreadPool() | |
{ | |
const int NUM_OF_TASKS = 15; | |
ThreadPool pool; | |
for (int i = 0; i < NUM_OF_TASKS; ++i) | |
{ | |
Task task(i); | |
pool.execute(task); | |
} | |
getchar(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment