I have been reading over the following tutorial: C++ Multithreading Tutorial. I have compiled the code in the tutorial that creates ten unique threads and print a string with the thread number.
Here is what the code looks like for those who don't want to open the link:
#include <iostream>
#include <thread>
static const int num_threads = 10;
//This function will be called from a thread
void call_from_thread(int tid) {
std::cout << "Launched by thread " << tid << std::endl;
}
int main() {
std::thread t[num_threads];
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
t[i] = std::thread(call_from_thread, i);
}
std::cout << "Launched from the main\n";
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
return 0;
}
When I run the code it compiles and the output is kind of random. It will launch each thread but it won't launch them in order.
I was reading the C++ reference on std::mutex and it sounds like that is what I need.
So, I was wondering if someone could give me a quick rundown over how to implement std:mutex in code like this to ensure that the threads don't use the same shared resource and to ensure that they launch in order.