I'm new to c++ and I was looking into some c++ cross-platform thread tutorials. I was looking into this: http://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/
and was trying to execute the following code:
#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;
}
The output I'm getting is the following and I can not understand why:
syd@syd-HP-Compaq-dx7500-Microtower:~/Desktop$ ./ref
Launched by thread Launched by thread Launched by thread Launched by thread Launched by thread 201
Launched by thread 5
Launched by thread 6
4
Launched by thread 7
3
Launched by thread 8
Launched from the main
Launched by thread 9
I understand that the numbers are random each time, but some times I get no numbers displayed and I wonder why?
Multithreading in C++ C++ 11 did away with all that and gave us std::thread. The thread classes and related functions are defined in the thread header file. std::thread is the thread class that represents a single thread in C++.
A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
Multithreading is the ability of a program or an operating system to enable more than one user at a time without requiring multiple copies of the program running on the computer. Multithreading can also handle multiple requests from the same user.
Can you create a C++11 thread with a lambda closure that takes a bunch of arguments? Yes – just like the previous case, you can pass the arguments needed by the lambda closure to the thread constructor.
all you need to do is adding a mutex and lock it in the proper position:
std::mutex mtx;
-
void call_from_thread(int tid) {
mtx.lock();
-----------------------------------------------------------
std::cout << "Launched by thread " << tid << std::endl;
-----------------------------------------------------------
mtx.unlock();
}
-
mtx.lock();
-----------------------------------------------------------
std::cout << "Launched from the main\n";
-----------------------------------------------------------
mtx.unlock();
refer to this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With