Interface Definition:
Public Interface Iloadbalance<t> { T Balance (); }
Realize:
Public classWeightobject<t>whereT:class { intweight; T Activator; PublicWeightobject (T activator,intweight) {Activator=Activator; Weight=weight; } Public intWeight {Get { returnweight; } Private Set { if(Value <=0) { Throw NewArgumentOutOfRangeException (); } Weight=value; } } PublicT Activator {Get { returnActivator; } Private Set { if(Value = =NULL) { Throw NewArgumentNullException (); } Activator=value; } } } Public classOrderloadbalance<t>: iloadbalance<t> { Private ReadOnly ObjectSyncRoot =New Object(); Private intGCD; Private intCurrentindex =-1; Private intCurrentweight =0; Private intMaxweight; Privatelist<weightobject<func<t>>> list =NewList<weightobject<func<t>>>(); PublicOrderloadbalance (ienumerable<weightobject<func<t>>>weightobjects) {list. AddRange (weightobjects); GCD=GETGCD (); Maxweight= list. Select (w =w.weight). Max (); } Private intgetgcd () {intGCD =1; intMinweight = list. Select (w =w.weight). Min (); for(inti =1; i < minweight; i++) { BOOLIsfound =true; foreach(varWeightobjectinchlist) { if(weightobject.weight% i! =0) {Isfound=false; Break; } } if(isfound) GCD =i; } returnGCD; } [MethodImpl (methodimploptions.synchronized)] PublicT Balance () {Lock(syncRoot) { while(true) {Currentindex= (Currentindex +1) %list. Count; if(0==currentindex) {Currentweight= Currentweight-GCD; if(0>=currentweight) {Currentweight=Maxweight; if(Currentweight = =0)returnlist[0]. Activator (); } } if(List[currentindex]. Weight >=currentweight) { returnList[currentindex]. Activator (); } } } } } Public classRandomloadbalance<t>: iloadbalance<t> {
Privaterandom random; Private intTotalweight; Privatelist<weightobject<func<t>>> list =NewList<weightobject<func<t>>>(); PublicRandomloadbalance (ienumerable<weightobject<func<t>>>weightobjects) {list. AddRange (weightobjects); Totalweight= list. Select (w =w.weight). Sum (); Random=NewRandom (); } PublicT Balance () {intr = Random. Next (totalweight) +1; intWeight =0; foreach(varIteminchlist) {Weight+=item. Weight; if(weight>=r) {returnitem. Activator (); } } returnlist[0]. Activator ();// } }
The above two methods can achieve a simple equalization algorithm, the first I refer to many predecessors of the writing, the second belongs to their own thinking. From the perspective of probability theory can satisfy the demand, and both of the efficiency is equal (I thought the second way to achieve faster, unfortunately, it turns out that this is not the case, may be random object to take the stochastic number is slow, I theoretically think that no lock will be faster), I personally think the method is better, the reason is that the discrete type is better, although the probability is good, but will be a continuous dense access to the same object. As a equalization algorithm, I think it's better to be more discrete. Because this can be better staggered dense access!!!
2 Kinds of load balancing algorithms