Concurrency and Multithreading in C++
Concurrency and multithreading in C++ allows you to run multiple threads of execution simultaneously within a single program. This can be useful for improving performance, as well as for handling tasks that require parallel processing. Here's an example of using multithreading in C++:
c++
#include <iostream>
#include <thread>
void print_message(std::string message, int delay) {
for (int i = 0; i < 10; i++) {
std::cout << message << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
}
}
int main() {
std::thread t1(print_message, "Thread 1", 500);
std::thread t2(print_message, "Thread 2", 1000);
t1.join();
t2.join();
return 0;
}
In this example, we're using the std::thread class to create two threads of execution, which will run the print_message function with different arguments. The print_message function prints a message to the console, waits for a specified delay, and then repeats this process 10 times. By running this function in multiple threads with different delays, we can create the illusion of multiple processes running simultaneously. We then use the join method to wait for both threads to complete before exiting the program. When you run this program, you should see two sets of messages printed to the console, one set with a delay of 500 milliseconds, and one set with a delay of 1000 milliseconds.
No comments:
Post a Comment