thread_get_id.cpp 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // https://cirosantilli.com/linux-kernel-module-cheat#cpp-multithreading
  2. //
  3. // Spawn some threads and print their ID.
  4. //
  5. // On Ubuntu 19.04, they ar large possibly non-consecutive numbers.
  6. #include <cstring>
  7. #include <iostream>
  8. #include <mutex>
  9. #include <thread>
  10. #include <vector>
  11. std::mutex mutex;
  12. void myfunc(int i) {
  13. // Mutex and flush to prevent the output from
  14. // different threads from interleaving.
  15. mutex.lock();
  16. std::cout <<
  17. i << " " <<
  18. std::this_thread::get_id() << std::endl
  19. << std::flush;
  20. mutex.unlock();
  21. }
  22. int main(int argc, char **argv) {
  23. std::cout << "main " << std::this_thread::get_id() << std::endl;
  24. std::vector<std::thread> threads;
  25. unsigned int nthreads;
  26. // CLI arguments.
  27. if (argc > 1) {
  28. nthreads = std::strtoll(argv[1], NULL, 0);
  29. } else {
  30. nthreads = 1;
  31. }
  32. // Action.
  33. for (unsigned int i = 0; i < nthreads; ++i) {
  34. threads.push_back(std::thread(myfunc, i));
  35. }
  36. for (auto& thread : threads) {
  37. thread.join();
  38. }
  39. }