Reputation: 11012
Consider the following sample program in which a loop is running;
int main()
{
for (int i = 0; i<= 300; ++i) {
}
}
Pretty basic, now let's suppose I want to print out the value of i
every second:
cout << "i= " << i << "\n";
A simple loop like the following might suffice, where "elaspedTime" is a ficticious integer containing the number of seconds the program has been running magically updated by the OS:
int lastTime = 0;
while (true) {
if (elapsedTime > lastTime) { // Another second has passed
cout << "i= " << "\n";
lastTime = elapsedTime;
}
}
The ultimate goal here is to give an output like the following (assuming the loop ran exactly 100 times per second because it was on an old, slow CPU):
$ ./myprog
i= 100
i= 200
i= 300
These are simple functions and routines, despite this, I see no way to perform such an operation in a "classical" c++ program which typically has just a main()
function. Despite the simplicity is this the point at which I need to learn multi-threading? Or, is it possible to call functions from main()
and not wait for their return but without that called function "hogging" the thread?
Upvotes: 0
Views: 1386
Reputation: 470
I'm curious what problem you're trying to solve though. Where did 'wanting to know how many iterations are done in a second' come from? Reason I'm asking is because the answer you'll be getting using either a single thread approach discussed at the top ( check clock - increment - check clock - increment ... check clock - print) or the multi-threaded approach, they both suffer from introducing overhead and uncertainty of your thread running. What I mean is: in both cases you'll have to be executing a bunch of extra stuff - clock() calls in single thread case and thread synchronization in a multi-threaded case. Both will influence the total number of iterations done in a second by your program (the number will be smaller), so you'll get an incorrect result. Moreover there's the Operating System whos thread scheduler is the decider when your thread runs and when it sleeps waiting for the next available quantum. And quantum is ~20-30 milliseconds, so a resulting error during time interval check could easily (probably on average) be at a few percent.
Would not it be easier and more natural to save the start time, then do all the iterations you need to do to process all your data (do all the work), then take a timestamp again and divide the total number of iterations by the time interval. Or is there something specific to the problem you're solving that this approach would not work?
Upvotes: 0
Reputation: 101506
If you want two functions to run at the same exact time independently of each other, you need to use threads. The example you've provided doesn't need to use threads to accomplish what you stated you wanted to accomplish, but based on your comments I think your question was a bit unclear.
Multithreading is something that is not mentioned in the C++03 Standard. There is some support for it in the latest C++11 Standard, but it's not end-all,be-all. The way multithreading is actually implemented is platform-specific. WinTel boxes do it one way, Linux/Intel boxes do it another. Two main approaches to writing multithreaded code are:
When just starting out, these days I'd recommend starting with a cross-platform library, so you can get many of the big picture concepts down without getting mired by platform-specific idiosyncrasies. One such library is Boost.Thread.
EDIT
Given that you are new to mutithreaded programming, I feel I should warn you: you are jumping down a deep rabbit hole with a blindfold on. Multithreadded programming is kind of like chess -- you can learn much of the basic syntax and system calls fairly quickly, but doing multithreaded programming right is something that will only come with a lot of study and practice. Multithreadded programming done correctly is one of the hardest things a programmer will ever face.
Also, please pay special attention to @CrazyEddie's comment below:
Once you switch from "function" to "task" though the story changes. It's very possible to do many tasks at once, depending on the task. Since event loops like the OP's usually spend most of their time sleeping, threads are usually only used for convenience rather than performance or necessity. I'm sure you know this, but the OP probably doesn't. OP needs to look up "asynchronous processing" and weigh the benefits/penalties of using threads vs non-blocking ops and event loops.
Upvotes: 3
Reputation: 168876
What's wrong with doing this? No multitasking required.
int lastTime = 0;
while (true) {
if (std::time() > lastTime) { // Another second has passed
cout << "i= " << i << "\n";
// potentially expensive code goes here, which updates "i"
lastTime = std::time();
}
}
Upvotes: 1