Day 14 of Learning C++: Multithreading and File I/O
Hello, dedicated learners! It's Day 14 of your incredible 100-day C++ learning journey, and today, we're delving into two important topics that can greatly expand the capabilities of your C++ programs: multithreading and file input/output (I/O).
1. Multithreading: Parallel Execution
Multithreading allows your program to execute multiple threads simultaneously, making efficient use of multi-core processors. It can improve the performance of CPU-bound tasks and enable concurrent execution of tasks.
Here's a simple example of using the C++11 threading library:
#include <iostream>
#include <thread>
void printNumbers() {
for (int i = 1; i <= 5; i++) {
std::cout << "Number: " << i << std::endl;
}
}
void printLetters() {
for (char letter = 'A'; letter <= 'E'; letter++) {
std::cout << "Letter: " << letter << std::endl;
}
}
int main() {
std::thread t1(printNumbers);
std::thread t2(printLetters);
t1.join(); // Wait for thread t1 to finish
t2.join(); // Wait for thread t2 to finish
return 0;
}
In this example, we create two threads (t1 and t2) that execute the printNumbers and printLetters functions concurrently.
2. File Input/Output (I/O): Working with Files
File I/O is essential for reading data from and writing data to external files. C++ provides several classes for file operations, including fstream, ifstream, and ofstream.
Here's an example of writing data to a file:
领英推荐
#include <iostream>
#include <fstream>
int main() {
std::ofstream outputFile("example.txt");
if (outputFile.is_open()) {
outputFile << "Hello, File I/O!" << std::endl;
outputFile.close();
} else {
std::cerr << "Unable to open the file." << std::endl;
}
return 0;
}
And here's an example of reading data from a file:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inputFile("example.txt");
if (inputFile.is_open()) {
std::string line;
while (std::getline(inputFile, line)) {
std::cout << "Read: " << line << std::endl;
}
inputFile.close();
} else {
std::cerr << "Unable to open the file." << std::endl;
}
return 0;
}
Key Takeaways for Day 14:
Multithreading enables parallel execution of tasks and efficient utilization of multi-core processors.
File I/O operations with fstream, ifstream, and ofstream allow reading from and writing to external files.
Next Steps:
For Day 15, let's explore more advanced C++ topics like networking and working with libraries to expand your programming horizons.
Keep up the fantastic work on your C++ journey! If you have questions or insights to share, feel free to reach out. Happy coding with multithreading and file I/O! ????
#CPP #cpp #cplusplus #programming #learningjourney #multithreading #fileio