Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambdas and threads

I've recently started using lambdas an awful lot within threads, and want to make sure I'm not setting myself up for thread-safety issues/crashes later. My usual way of using them is:

class SomeClass {  
    int someid;  
    void NextCommand();  
    std::function<void(int, int)> StoreNumbers;  
    SomeClass(id, fn); // constructor sets id and storenumbers fn  
}

// Called from multiple threads  
static void read_callback(int fd, void* ptr)  
{  
    SomeClass* sc = static_cast<SomeClass*>ptr;  
    ..  
    sc->StoreNumbers(someint,someotherint); // voila, thread specific storage.  
}  

static DWORD WINAPI ThreadFn(LPVOID param)  
{  
    std::list<int> ints1;  
    std::list<int> ints2;  
    auto storenumbers = [&] (int i, int i2) {  
        // thread specific lambda.  
        ints1.push_back(i);  
        ints2.push_back(i2);  
        };  
    SomeClass s(id, storenumbers);  
    ...  
    // set up something that eventually calls read_callback with s set as the ptr. 
}  

ThreadFn is used as the thread function for 30-40 threads.

Is this acceptable? I usually have a few of these thread-specific lambdas that operate on a bunch of thread specific data.

Thank you!

like image 211
Robert Stone Avatar asked Jan 17 '26 00:01

Robert Stone


1 Answers

There's no problem here. A data access with a lambda is no different to a data access with a named function, through inline code, a traditional functor, one made with bind, or any other way. As long as that lambda is invoked from only one thread at a time, I don't see any evidence of thread-related problems.

like image 147
Puppy Avatar answered Jan 19 '26 15:01

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!