这将是一个很长的故事,但也许你们中的一些人想研究这个案例.
我正在研究并行图算法开发.我选择了一个名为STINGER的尖端HPC并行图数据结构.STINGER的使命声明如下:
“STINGER should provide a common abstract data structure such that the
large graph community can quickly leverage each others’ research
developments. […] Algorithms written for STINGER can easily be
translated/ported between multiple languages and frameworks […] It
is recognized that no single data structure is optimal for every graph
algorithm. The objective of STINGER is to configure a sensible data
structure that can run most algorithms well. There should be no
significant performance reduction for using STINGER when compared with
another general data structure across a broad set of typical graph
algorithms.”
STINGER可能非常有效并且适用于共享内存并行性.另一方面,它不是非常抽象,通用或简洁. STINGER提供的界面对我来说不能令人满意,原因如下:它太冗长了(函数需要的参数对我的情况来说并不重要);它仅模拟有向图,而我需要一个无向图;和其他原因.
但是,我不愿意自己实现一个新的并行图数据结构.
所以我已经开始用我自己的Graph类封装一个STINGER实例.例如,要检查是否存在无向边,我现在可以调用Graph :: hasEdge(节点u,节点v)而不是写入我的算法:
int to = stinger_has_typed_successor(stinger, etype, u, v);
int back = stinger_has_typed_successor(stinger, etype, v, u);
bool answer = to && back;
到目前为止,这一点运作良好.现在到迭代的话题.
STINGER通过宏实现遍历(迭代节点,边缘,节点的入射边缘等).例如,你写
STINGER_PARALLEL_FORALL_EDGES_BEGIN(G.asSTINGER(), etype) {
node u = STINGER_EDGE_SOURCE;
node v = STINGER_EDGE_DEST;
std::printf("found edge (%d, %d)", u, v);
} STINGER_PARALLEL_FORALL_EDGES_END();
这里STINGER_PARALLEL_FORALL_EDGES_BEGIN扩展为
do { \
\
\
for(uint64_t p__ = 0; p__ < (G.asSTINGER())->ETA[(etype)].high; p__++) { \
struct stinger_eb * current_eb__ = ebpool + (G.asSTINGER())->ETA[(etype)].blocks[p__]; \
int64_t source__ = current_eb__->vertexID; \
int64_t type__ = current_eb__->etype; \
for(uint64_t i__ = 0; i__ < stinger_eb_high(current_eb__); i__++) { \
if(!stinger_eb_is_blank(current_eb__, i__)) { \
struct stinger_edge * current_edge__ = current_eb__->edges + i__;
该宏隐藏了数据结构的肠子,这些肠子显然需要完全暴露以进行有效(并行)迭代.有各种组合的宏,包括STINGER_FORALL_EDGES_BEGIN,STINGER_READ_ONLY_FORALL_EDGES_BEGIN,STINGER_READ_ONLY_PARALLEL_FORALL_EDGES_BEGIN ……
是的我可以使用这些宏,但我想知道是否有更优雅的方式来实现迭代.如果我希望有一个界面,它看起来就像
G.forallEdges(readonly=true, parallel=true, {..})
GraphIterTools.forallEdges(G, readonly=true, parallel=true, {...})
其中{…}只是一个函数,一个闭包或一个“代码块”,然后可以适当地执行.但是,我缺乏实施此操作的C经验.我想知道你可以在这个问题上给我什么建议.也许还有“你应该使用宏,因为……”.
最佳答案 利用现有的宏,您可以在图类上实现一个成员函数,如下所示:
template<typename Callback>
void forallEdges(int etype, Callback callback)
{
STINGER_PARALLEL_FORALL_EDGES_BEGIN(this->asSTINGER(), etype) {
node u = STINGER_EDGE_SOURCE;
node v = STINGER_EDGE_DEST;
// call the supplied callback
callback(u, v);
} STINGER_PARALLEL_FORALL_EDGES_END();
}
然后定义一个回调函数并将其传递给您的新方法:
void my_callback(node u, node v) { ... }
...
G.forallEdges(etype, my_callback);
或者在C 11中你可以使用lambda函数:
G.forallEdges(etype, [](node u, node v) { ... });