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 ライブラリを使用して、2 つの個別のスレッドを作成できます。各スレッドは、乗算の半分を実行する必要があります。次のソリューションをまとめることができました。

#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 ライブラリの実装では、2 つのスレッドの作業を並列化する必要があります。また、この例は、わずかな変更で N スレッドに一般化できます。

于 2013-11-21T02:02:18.620 に答える