并行程序设计作业7/5

#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;
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值