hi, how would you get a certain part of code to run while the program is waiting for the input?

string in;
int n1 = 0;
n1++ // get this part of code to loop while the program is waiting for the input
cin >> in

thanks.

Dani AI

Generated

Short answer: run the work you want done while waiting for input in a background thread, or—if you only need timing—take a timestamp before the blocking read and one after. That covers 's suggestion (background thread) and 's simpler timing idea. For modern, portable C++ use the C++11 thread and chrono facilities; Boost provides similar APIs if you must support older compilers; on Windows the native high-resolution API is QueryPerformanceCounter. (en.cppreference.com)

A safe, minimal pattern (C++11+) is: spawn a worker thread that increments an atomic counter and sleeps briefly to avoid busy-waiting; block on input in the main thread; set a stop flag and join the worker when input arrives.

#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
#include <string>

int main() {
    std::atomic<bool> stop{false};
    std::atomic<unsigned long long> n1{0};

    std::thread worker([&](){
        while (!stop.load(std::memory_order_relaxed)) {
            ++n1;
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }
    });

    std::string in;
    std::getline(std::cin, in);   // blocking read
    stop.store(true);
    worker.join();

    std::cout << "n1 = " << n1.load() << '\n';
}

Use std::atomic for shared counters to avoid data races, std::this_thread::sleep_for to prevent CPU-hogging, and always join() or detach() threads (destroying a joinable thread calls std::terminate). (cs.helsinki.fi)

If you only need elapsed milliseconds (no concurrent work), record a std::chrono::steady_clock::now() before the input and compute the difference after with duration_cast<milliseconds>. That is simpler and less error-prone. If Dev-C++/your compiler is old, consider Boost.Thread/Boost.Chrono or the platform APIs mentioned above (as others suggested). Also avoid editing system headers. This addresses ’s original need while expanding on suggestions from and . ()

Recommended Answers

All 18 Replies

Have line 3 run in another thread. Join the threads after line 4

i dont think that would work. Are you talking about putting line 3 in another function? Cause if you are, that wouldnt work.

No, he means another thread. C++ currently doesn't come with a platform independent way to spawn threads, so you'll have to either rely on Operating System API calls, or use a library (I recommend Boost).

There are plenty of examples of both ways and I suggest reading some tutorials on multi-threading w/ C++ first.

Also, may I ask why you want to do this in the first place?

If it's for measuring the time the users takes to produce some input it's much easier to check the time before you ask for input, check it again right after input has been received and simply subtract the two.

Take a look at this if that is the case:


If you're interested in threads you could use the CreateThread function. You have to read a lot...

thanks for all the help, but i need the timer to count in milliseconds. heres some code i pulled up

double time = .001;
time = time + .001;
Sleep(1)

if(!cin)
{
}
else
{
   cin >> n1;
}

Judging from the code you wrote I feel like you don't really know what you're doing.
So please make sure you understand my code instead of ignorantly copying it.

#include <iostream>
#include <time.h>

int main()
{
    time_t before = time(NULL);

    char input;
    std::cin >> input;

    //time_t after = time(NULL);
    //std::cout << difftime(after, before) << " seconds passed";
    std::cout << difftime(time(NULL), before) << " seconds passed";
}

Yes, i understand the code and its exacly what i need but how would you change the seconds into milliseconds?

The ctime library only supports a granularity down to seconds. For milliseconds you must either use a non-portable library (such as GetTickCount()). The Boost Date_Time library offers sub-second resolution if the underlying platform does as well (which Windows does).

Standard solutions include dividing the result by CLOCKS_PER_SEC (be sure to cast either of the operands to double) and hoping for the best, or taking advantage of the new <chrono> stuff in C++0x. Both are non-portable at this time. The former is unconditionally non-portable and the latter depends on adoption of the upcoming standard in compilers.

Sounds like a great opportunity to use boost!

ok, so are they telling you to put the GetTickCount() syntax in the time.h header file?

ok, so are they telling you to put the GetTickCount() syntax in the time.h header file?

Um...what?

well, they had the code, but they didnt say where to put it.

Don't modify your header files!!!! At least the ones that come with the compiler anyway.

well, they had the code, but they didnt say where to put it.

Wow. Just...wow.

ok listen, would at least ONE of you guys look at that link that Narue posted? if you guys know anything about what to do with the code, please share.

Good god, are you really that clueless? It's the same damn thing as Insensus' example, just with GetTickCount() instead of time():

#include <iostream>
#include <windows.h>
 
int main()
{
    DWORD before = GetTickCount();
 
    std::cin.get();
 
    std::cout << GetTickCount() - before << " milliseconds passed";
}
commented: Getting there in the end +17

ok, thanks you guys for all the help. i really do appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.