Lambdas and threads
Lambdas and threads
我最近开始在线程中大量使用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,我就看不到任何与线程相关的问题。
相关文章:
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 为什么 Clang 不允许"and"作为函数名称?
- 位阵列上的快速AND运算
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- BoostPython and CMake
- OpenSSL BIO and SSL_read
- Gurobi GRBModel and GRBmodel in C++
- C++ Win32 Threads
- std::visit and std::variant usage
- SHBrowseForFolder with BIF_BROWSEFORCOMPUTER and SHGetPathFr
- Directx12 and keystrokes
- Threads with Classes and std::packaged_task
- Flask, boost::python and threads
- htop and OpenMP threads
- Python GIL and threads
- C++ threads and classess
- QtScript and threads
- Lambdas and threads