Вы можете использовать библиотеку 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 потоков с незначительными изменениями.
n! = n * (n-1) * ... * (n/2) * ... * 1. У вас может быть один процессор, который выполняет первые n/2-умножения, другой процессор сделает все остальное, затем умножьте 2 результата вместе. –