David Roberts
David Roberts

Reputation: 145

Creating a delay() function using <thread> (C++)

I'm trying to create a delay function in C++, using a "delay(int x)" form factor. Here is the program I am running currently:

#include <chrono>
#include <thread>
#include <iostream>
using namespace std;

typedef chrono::duration<int, ratio<1,1000> > ms; //defines a ms

void f(int x){
    ms xmillisecs (x);  // defines the duration xmillisecs (which is x milliseconds)
    this_thread::sleep_for(xmilisecs);  // delays for x milliseconds
}

void delay(int delaytime){
    thread mythread(f,delay time);  // starts the above thread (the one with x ms delay)
}

int main(){
    cout<<"I hope this works";
    delay(1000);
    cout<<"This happens one second later";
    cin.get();
    return 0;
}

This compiles without error messages, but terminal gives the following output, which is clearly not what a delay() function should do:

libc++abi.dylib: terminating
I hope this worksAbort trap: 6

What's going on here?

Upvotes: 0

Views: 1714

Answers (1)

Michael J
Michael J

Reputation: 7949

The std::this_thread::sleep_for() function only causes the calling thread to sleep.

In your case, you are creating a second thread which sleeps while the thread running main() continues executing.

It should look more like this:

void delay(int delaytime)
{ 
    std::this_thread::sleep_for(std::chrono::milliseconds(delaytime)); 
}

Upvotes: 2

Related Questions