Skip to content

Instantly share code, notes, and snippets.

@joeld42
Created April 8, 2019 17:30
Show Gist options
  • Save joeld42/673fa241cbd3b8db241f5e5b8d36f355 to your computer and use it in GitHub Desktop.
Save joeld42/673fa241cbd3b8db241f5e5b8d36f355 to your computer and use it in GitHub Desktop.
Example threading in c++
// c++ -std=c++11 thread.cpp -o thread && ./thread
#include <iostream>
#include <algorithm>
#include <vector>
#include <thread>
class TraceTile
{
public:
int tileNum = 0;
void renderTile() {
std::cout << "will render tile " << tileNum << std::endl << std::flush;
// TODO: Actually render the tile
std::this_thread::sleep_for (std::chrono::seconds(1));
std::cout << "done with tile" << tileNum << std::endl << std::flush;
}
};
int main()
{
std::vector<TraceTile> tiles;
for (int i=0; i < 10; i++) {
TraceTile t;
t.tileNum = i;
tiles.push_back( t );
}
std::cout << "Single threaded way ------------- " << std::endl;
for (TraceTile &t : tiles) {
t.renderTile();
}
std::cout << "multi threaded way ------------- " << std::endl;
std::vector<std::thread> renderThreads;
for (TraceTile &t : tiles) {
renderThreads.push_back( std::thread( &TraceTile::renderTile, t ) );
}
for (std::thread &rndr : renderThreads ) {
rndr.join();
}
std::cout << "all done" << std::endl;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment