简体   繁体   中英

How to pack std::thread with template constructor and lambda function?

Why is data in func() repeated?

#include <memory>
#include <thread>
#include <unistd.h>
#include <vector>

    struct Data {
    int id;
};

class Thread {
    public:
    template <class Function, class... Args>
    Thread(Function &&f, Args &&...args) noexcept
        : internal_{ [func = std::forward<Function>(f), &args...]() {
            func(args...);
        } }
    {
    }

    private:
    std::thread internal_;
};

void func(Data *data)
{
    printf("                in thread, data: %p, id: %d\n", data, data->id);
}

int main()
{
    static Data data[8];
    std::vector<Thread *> threads;
    volatile int i = 0;
    for (i = 0; i < 8; i++) {
        data[i].id = i;
        printf("out thread, data: %p\n", &data[i]);
        auto tmp = new Thread(func, &data[i]);
        threads.emplace_back(tmp);
    }

    sleep(100);
    return 0;
}
out thread, data: 0x562bb497d040
out thread, data: 0x562bb497d044
                in thread, data: 0x562bb497d044, id: 1
out thread, data: 0x562bb497d048
                in thread, data: 0x562bb497d048, id: 2
out thread, data: 0x562bb497d04c
                in thread, data: 0x562bb497d04c, id: 3
out thread, data: 0x562bb497d050
                in thread, data: 0x562bb497d04c, id: 3
out thread, data: 0x562bb497d054
                in thread, data: 0x562bb497d054, id: 5
out thread, data: 0x562bb497d058
                in thread, data: 0x562bb497d054, id: 5
                in thread, data: 0x562bb497d058, id: 6
out thread, data: 0x562bb497d05c
                in thread, data: 0x562bb497d05c, id: 7
Thread(Function &&f, Args &&...args) noexcept
    : internal_{ [func = std::forward<Function>(f), &args...]() {
        func(args...);  // _________________________^_______
    } }
{
}

You dump the local parameter/variable &args captured by reference. This is a reference to a destroyed object, undefined behavior. Remove & to capture the variable by value and you will get proper addresses of data[i] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM