#include<iostream>
#include<unistd.h>
#include <pthread.h>
#include <string.h>
#include <map>
using namespace std;
int num_cores;
map<long long,long long> id_to_thread;
map<long long,long long> thread_to_id;
int value[100];
int core_sum=0;
int divisor=2,core_difference=1;
void *add(void *arg){
//sleep(1);
if(thread_to_id[pthread_self()]%divisor==0ll){
//jieshou
value[thread_to_id[pthread_self()]]+=value[thread_to_id[pthread_self()]+core_difference];
//cout<<thread_to_id[pthread_self()]<<"*"<<thread_to_id[pthread_self()]+core_difference<<endl;
pthread_exit(NULL);
}
else{
//fasong
pthread_exit(NULL);
}
return NULL;
}
int main(){
cout<<"please cin the sum of core(power of two)"<<endl;
cin>>core_sum;
cout<<"please cin the value of each cores"<<endl;
for(int i=0;i<core_sum;++i){
cin>>value[i];
}
//sleep(10);
while(divisor<=core_sum){
for(int i=0;i<core_sum;i+=core_difference){
pthread_t tid;
pthread_create(&tid, NULL, add, NULL);
id_to_thread[i]=tid;
thread_to_id[tid]=i;
}
for(int i=0;i<core_sum;i+=core_difference){
pthread_join(id_to_thread[i],NULL);
}
for(int i=0;i<core_sum;++i){printf("%d ",value[i]);}
printf("\n");
divisor*=2;
core_difference*=2;
}
cout<<"The final result is "<<value[0]<<endl;
}
文章评论