There is a program that I am doing on a Parking system in which, I want to implement a background thread that reads data from a file and gives a real-time output of the count of data on the console.
can someone please help with some kind of example because I am a bit confused that how to implement this?
Though I doubt that a thread is usefull here. Threads let you do two or more things at the same time, but is usually not good for 'speed up' things...
I will respectfully disagree.
Threads are great at speeding things up, if the thing you are attacking is a good candidate for it. A dumb example that is easy to understand is a linear search through unsorted data. If you have a shiny new I9 CPU with 20 cores, you can divide your data pile into 20 chunks and search each one 20 times faster.
There are a lot of algorithms that benefit from a simple division of labor approach with the high core count on modern hardware.
I do agree that a thread is not useful here. If it were a live stream and not a file, maybe, or a streamed file that is being written as you are reading it (more complexity to handle!) on a SSD, "maybe" a thread would help. Hard to say without details.
#include <string>
#include <iostream>
#include <thread>
usingnamespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}