Question:
As much as I use threads, I never join()
-il … In my understanding, to implement multithreading thread
-s, you need to "let go free swimming" using detach()
, and regulate access to shared memory areas with mutexes.
Please explain where I am wrong?… After all, it is recommended to use join()
everywhere, but I don’t understand what is the point of calling a thread with join()
in the function and thereby stopping its execution until the thread has completed… Where is multithreading then?
[UPDATE]
After reading the answers, I still do not understand where is multithreading, for example, in this code?
#include <iostream>
#include <thread>
#include <mutex>
std::mutex m_console;
void Log(){
for( int i = 0; i < 127; i++){
std::lock_guard<std::mutex> lock(m_console);
std::cout << i << std::endl;
}
}
void Lag(){
for( char i = 0; i < 127; i++){
std::lock_guard<std::mutex> lock(m_console);
std::cout << i << std::endl;
}
}
int main(int argc, char *argv[]){
std::thread(Log).join();
std::thread(Lag).join();
for( int i = 0; i < 127; i++){
std::lock_guard<std::mutex> lock(m_console);
std::cout << "azaza" << std::endl;
}
system("pause");
return 0;
}
If everything is done serially, where is the parallelization that threads exist for? Even if the locks are removed, the information in the console is not shuffled as expected…
Answer:
Depends on exactly what you need. For example, you parallelized some calculations – and what should you do now? For example, your threads each count some value, which then needs to be summed up. How do you do this by sending them to detach
? will you constantly poll for some flags that these threads should set? 🙂
Your threads should have been called something like this:
std::thread Lo(Log);
std::thread La(Lag);
for( int i = 0; i < 127; i++){
std::cout << "azaza" << std::endl;
}
Lo.join();
La.join();
Just keep in mind that mutexes are not needed there, cout
is already smart enough, and that you simply won’t see anything with these 127 numbers – the first thread will whistle while the second one is being created … Either make them bigger, or add, for example, a small delay …