Skip to content

Chapter 3 - Timer example wrongly captures by reference #30

@jvillasante

Description

@jvillasante

Here's the constructor:

Timer(const Duration interval, const Callback& callback) {
        auto value = duration_cast<milliseconds>(interval);
        sync_cout << "Timer: Starting with interval of " << value << std::endl;

        t = std::jthread([&](std::stop_token stop_token) {
            while (!stop_token.stop_requested()) {
                sync_cout << "Timer: Running callback " << val.load() << " ...\n";
                val++;
                callback();

                sync_cout << "Timer: Sleeping...\n";
                std::this_thread::sleep_for(interval);
            }
            sync_cout << "Timer: Exit\n";
        });
    }

In there the lambda for the thread captures everything by reference, which means that interval used below is long gone when the thread runs and the timer does not sleeps at all. Here's the correct code (capturing value by value:

Timer(const Duration interval, const Callback& callback) {
        auto value = duration_cast<milliseconds>(interval);
        sync_cout << "Timer: Starting with interval of " << value << std::endl;

        t = std::jthread([&, value](std::stop_token stop_token) {
            while (!stop_token.stop_requested()) {
                sync_cout << "Timer: Running callback " << val.load() << " ...\n";
                val++;
                callback();

                sync_cout << "Timer: Sleeping...\n";
                std::this_thread::sleep_for(value);
            }
            sync_cout << "Timer: Exit\n";
        });
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions