mirror of
https://github.com/cirosantilli/linux-kernel-module-cheat.git
synced 2026-01-23 10:15:57 +01:00
userland: move more multithreading from cpp-cheat!
Convert infinite_loop.c into loop.c. Keep all examples fast by default!
This commit is contained in:
29
userland/cpp/thread_get_id.cpp
Normal file
29
userland/cpp/thread_get_id.cpp
Normal file
@@ -0,0 +1,29 @@
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user