0

我想使用递归函数实现搜索树。在每个节点中,我评估一个函数Pass_or_Die。如果Pass然后该节点扩展到n更多的分支,否则它会死亡。假设一个节点以一定的固定概率通过。

假设我有一台带M > n内核的机器。我想在搜索树上使用我所有的核心。下面的代码显示了一个搜索树的简单示例。

我对这个使用 openMP 的示例的问题是:1)该程序仅使用n内核。所以它不会使用所有可用的内核。

2)从输出看来,搜索树是逐步筛选的。这意味着首先检查级别 1 的所有节点,然后检查级别 2 的所有节点,等等。我希望将重点放在运行第一个节点及其子树上,直到它们死亡或到达末尾,然后关注另一个节点。

我也对使用 openMP 替代方案的解决方案持开放态度。

#include <stdio.h> 
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "omp.h"

int n = 3;

// Pass with probability prob/100
int Pass_or_Die(int prob)
{
    int max = 100;
    if ((rand()%max)>(max-prob))
        return 1;
    else
        return 0;
}

// extend the node if Pass, kill it if Die. Print current thread in use, current node and PASS or DIE
void extend_node(int base_node, int extension)
{
    // extend the node
    base_node = base_node*10+extension;

    // get thread id number
    int th_id = omp_get_thread_num();

    // just some noise
    sleep(1);

    // if true, then the tree reaches the end, so do not extend
    if (base_node > 100000)
        return;

    // if Pass, then extend the tree. Pass with probability 0.2
    if (Pass_or_Die(20))
    {
        printf("th_id %d - %d PASS\n ", th_id, base_node);
#pragma omp target teams distribute parallel for
        for (int i = 1; i <= n; ++i)
        {
            extend_node(base_node, i);
        }
    }
    else
        printf("th_id %d - %d DIE\n ", th_id, base_node);
    return;
}


int main (int argc, char *argv[]) {

#pragma omp target teams distribute parallel for
    for (int i = 1; i <= n; ++i)
    {
        extend_node(0, i);
    }

    return 0;
}
4

0 回答 0