我知道std::queue默认使用std::deque作为其内部容器。我找不到TBB的相同信息。
我有一个遗留的多线程应用程序,它当前使用std::queue>周围的线程安全包装器来存储相对较大的对象(58字节)。我目前正在寻找更好的替代方案来提高性能。
一种选择是摆脱链表,使用默认的std::deque作为内部容器,并从指向对象的指针切换为按值存储对象。在块中分配std::deque会在内存方面扩展得更好。元素的数量增加。此外,从缓存的角度来看,拥有几个连续的元素会很有帮助。
另一种选择是使用TBB的concurrent_bounded_queue。但是我没有足够的信息来知道将我的对象存储为值是否是一个可行的选择。
也欢迎任何替代建议。
发布于 2021-07-14 14:22:23
您可以将对象作为值存储在tbb::concurrent_bounded_queue中。您可以参考下面的示例代码来实现。
#include <tbb/concurrent_queue.h>
#include <tbb/concurrent_priority_queue.h>
#include <iostream>
static int value=0;
static int obj_count=0; // count of objects
class Myclass{
public:
int myarray[10];
Myclass()
{
for(int i=0;i<10;i++){
myarray[i]=value++; //initializing the values of myarray for each new object
}
}
void show()
{
std::cout<< " Values of object "<< (++obj_count ) <<" are: ";
for(int i=0;i<10;i++){
std::cout<<myarray[i]<<" "; // printing the data values of myarray object
}
std::cout<<std::endl;
}
};
int main()
{
Myclass m[10];
tbb::concurrent_bounded_queue<Myclass> queue; // creatiing a concurrent_bounded_queue of type "Myclass"
for(int i=0;i<10;++i){
queue.try_push(m[i]); //pushing each Myclass object into the concurrent_bounded_queue
}
for(int i=0;i<10;i++){
Myclass val;
if(queue.try_pop(val)) //pops it from the queue, assigns it to destination, and destroys the original value.
{
val.show(); //To print/access the data of myarray for each popped Myclass object.
}
}
std::cout<< std::endl;
return 0;
}
编译和执行可以像这里所附的截图链接-->中所示。compilation and execution
我希望这对你有帮助。
谢谢,Santosh
https://stackoverflow.com/questions/68266779
复制相似问题