Skip to content

Instantly share code, notes, and snippets.

@jpret
Created November 11, 2021 15:52
Show Gist options
  • Select an option

  • Save jpret/456b900f380ae610b2fcb19907d62870 to your computer and use it in GitHub Desktop.

Select an option

Save jpret/456b900f380ae610b2fcb19907d62870 to your computer and use it in GitHub Desktop.
Testing threads in c++
#include <chrono>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
// remember to add -pthread to the compile options.
// Run example: https://godbolt.org/z/Efnzxq9a1
int main() {
// Start
std::cout << "MAIN START" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
// Vector for thread pool
std::vector<std::unique_ptr<std::thread>> pool;
// Create each thread
for (int id = 0; id < 10; id++) {
// Push the lambda to execute into the thread and store in the pool
pool.push_back(std::make_unique<std::thread>([id]() {
std::cout << "Thread[" << id << "] START" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Thread[" << id << "] END" << std::endl;
}));
}
// Print main thread
auto mid = std::chrono::high_resolution_clock::now();
std::cout << "MAIN THREAD time elapsed: "
<< std::chrono::duration<double, std::milli>(mid - start).count()
<< " ms" << std::endl;
// Join all threads
for (auto &thread : pool) thread->join();
// Print time elapsed
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Elapsed time: "
<< std::chrono::duration<double, std::milli>(end - start).count()
<< " ms" << std::endl;
// End
std::cout << "MAIN END" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment