0

我有一个简单的问题要问你。我编写了这段代码来计算一个数字的阶乘,而无需递归。

int fact2(int n){
    int aux=1, total = 1;
    int i;
    int limit = n - 1;
    for (i=1; i<=limit; i+=2){
        aux = i*(i+1);
        total = total*aux;
    }
    for (;i<=n;i++){
        total = total*i;
    }
return total;

}

如您所见,我的代码使用循环展开来优化执行中的时钟周期。现在我被要求在同一代码中添加双向并行性,知道怎么做吗?

4

1 回答 1

2

您可以使用 ptherads 库来创建两个单独的线程。每个线程应该做一半的乘法。我可以整理以下解决方案。

#include <pthread.h>

typedef struct {
    int id;
    int num;
    int *result;
} thread_arg_t;

void* thread_func(void *arg) {
    int i;
    thread_arg_t *th_arg = (thread_arg_t *)arg;
    int start, end;
    if(th_arg->id == 0) {
        start = 1;
        end = th_arg->num/2;
    } else if (th_arg->id == 1) {
        start = th_arg->num / 2;
        end = th_arg->num + 1;
    } else {
        return NULL;
    }
    for(i=start; i < end; i++) {
            th_arg->result[th_arg->id] *= i;
    }
    return NULL;
}

int factorial2(int n) {
    pthread_t threads[2];
    int rc;
    int result[2];
    thread_arg_t th_arg[2];
    for(i=0; i<2; i++) {
        th_arg[i].id = i;
        th_arg[i].num = n;
        th_arg[i].result = result;
        rc = pthread_create(&threads[i], NULL, thread_func, (void *)&th_arg[i]);
        if (rc){
         printf("pthread_create() failed, rc = %d\n", rc);
         exit(1);
      }
    }

    /* wait for threads to finish */
    for(i=0; i<2; i++) {
      pthread_join(thread[i], NULL);

    /* compute final one multiplication */
    return (result[0] * result[1]);
}

pthread 库实现应该为您处理并行化两个线程的工作。此外,这个例子可以推广到 N 个线程,只需稍作修改。

于 2013-11-21T02:02:18.620 回答