场景需求
解决方案
通过锁+条件变量的方式来保证线程会按照特定的顺序执行。后续其实可以考虑如何封装一下,只需要传递需要线程数(threads_count)和所处理事件(task),然后自动异步执行。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
const int NUM_THREADS = 3; // 3 thread
std::mutex mtx;
std::condition_variable cv;
int current_number = 0;
struct picture
{
int val;
picture(int v) : val(v) {}
/* data */
};
void processPic(int thread_id, std::vector<picture> pictures) {
for (;;) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [&]() { return current_number % NUM_THREADS == thread_id || current_number > pictures.size(); });
if (current_number >= pictures.size()) {
break;
}
std::cout << pictures[thread_id].val << std::endl;
++current_number;
cv.notify_all();
}
}
int main() {
std::thread threads[NUM_THREADS];
std::vector<picture> pictures{};
for (int i = 0; i < NUM_THREADS; ++i) {
threads[i] = std::thread(processPic, i, pictures);
}
for (int i = 0; i < NUM_THREADS; ++i) {
threads[i].join();
}
return 0;
}