Search code examples
c++multithreadingc++17c++-chrono

Why can't I use chrono library?


Hello I am doing some easy exercise with thread, I want my t1 to sleep 2 seconds but I am getting this error: unable to find numeric literal operator ‘operator""s’

How is that possible?

#include <iostream>
#include <chrono>
#include <thread>

void printt1(int i)
{   std::this_thread::sleep_for(2s);
    std::cout << i<<std::endl;
}
int main()
{
    std::thread t1(printt1,1);
    std::thread t2([](std::thread& t1) { t1.join();std::cout << 2<<std::endl; });
    std::thread t3([](std::thread& t2) { t2.join();std::cout << 3<<std::endl; });
    t3.join();
    return 0;
}

Solution

  • From https://en.cppreference.com/w/cpp/symbol_index/chrono_literals:

    These operators are declared in the namespace std::literals::chrono_literals, where both literals and chrono_literals are inline namespaces. Access to these operators can be gained with using namespace std::literals, using namespace std::chrono_literals, and using namespace std::literals::chrono_literals.

    So just add using namespace std::literals::chrono_literals; to your file and you should be good to go.


    Edit:

    Regardless to the above issue, you're constructing the threads t2 and t3 incorrectly. Instead of a lambda that accepts a std::thread& as an argument, you probably meant to capture it in the lambda by reference as such:

        std::thread t1(printt1,1);
        std::thread t2([&t1]() { t1.join();std::cout << 2<<std::endl; });
        std::thread t3([&t2]() { t2.join();std::cout << 3<<std::endl; });
        t3.join();