Lambdas and threads

Lambdas and threads

本文关键字:threads and Lambdas      更新时间:2023-10-16

我最近开始在线程中大量使用lambda,并希望确保以后不会出现线程安全问题/崩溃。我通常使用它们的方式是:

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用作30-40个线程的线程函数。

这可以接受吗?我通常有一些这样的线程特定的lambda,它们对一堆线程特定的数据进行操作。

谢谢!

这里没有问题。通过内联代码、传统函子、bind或任何其他方式,使用lambda的数据访问与使用命名函数的数据访问没有什么不同。只要每次只从一个线程调用lambda,我就看不到任何与线程相关的问题。