Thread Exercise: Write a program that creates a simple thread in C++.
Solution:
#include <iostream>
#include <thread>
void threadFunction() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(threadFunction);
t.join();
std::cout << "Main thread exiting..." << std::endl;
return 0;
}
Explanation:
- We define a function threadFunction() which will be executed by the thread.
- In the main() function, we create a thread t and pass threadFunction to its constructor.
- We use t.join() to wait for the thread to finish execution before the main thread exits.