Files
linux-kernel-module-cheat/userland/cpp/thread_get_id.cpp
Ciro Santilli 六四事件 法轮功 e0fb39c92a userland: move more multithreading from cpp-cheat!
Convert infinite_loop.c into loop.c. Keep all examples fast by default!
2019-09-07 00:00:03 +00:00

30 lines
701 B
C++

// https://cirosantilli.com/linux-kernel-module-cheat#cpp-multithreading
//
// Spawn some threads and print their ID.
//
// On Ubuntu 19.04, they ar large possibly non-consecutive numbers.
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
std::mutex mutex;
void myfunc(int i) {
mutex.lock();
std::cout << i << " " << std::this_thread::get_id() << std::endl;
mutex.unlock();
}
int main() {
std::cout << "main " << std::this_thread::get_id() << std::endl;
std::vector<std::thread> threads;
for (unsigned int i = 0; i < 4; ++i) {
threads.push_back(std::thread(myfunc, i));
}
for (auto& thread : threads) {
thread.join();
}
}