Skip to content

Instantly share code, notes, and snippets.

@tomas789
Last active December 24, 2015 19:59
Show Gist options
  • Save tomas789/6855047 to your computer and use it in GitHub Desktop.
Save tomas789/6855047 to your computer and use it in GitHub Desktop.
Parallel processing
#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>
#include <vector>
class example {
std::atomic<std::size_t> counter;
std::size_t stop = 160;
std::mutex cout_guard;
void job(std::size_t i) {
std::lock_guard<std::mutex> guard(cout_guard);
std::cout << "Job " << i << " from "
<< std::this_thread::get_id()
<< std::endl;
}
void worker() {
std::size_t current;
while ((current = counter++) < stop)
job(current);
}
public:
example() : counter(ATOMIC_VAR_INIT(0)) { }
void run() {
std::vector<std::thread> threads;
for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i)
threads.emplace_back(&example::worker, this);
for (auto it = threads.begin(); it < threads.end(); ++it)
it->join();
}
};
int main(int argc, char * argv[]) {
example m;
m.run();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment