Coverage Report

Created: 2026-11-22 14:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/home/runner/work/charm/charm/src/ck-ldb/DistributedLB.C
Line
Count
Source
1
/**
2
 * Author: gplkrsh2@illinois.edu (Harshitha Menon)
3
 * A distributed load balancer.
4
*/
5
6
#include "DistributedLB.h"
7
8
#include "elements.h"
9
10
extern int quietModeRequested;
11
12
static void lbinit()
13
552
{
14
552
  LBRegisterBalancer<DistributedLB>("DistributedLB", "The distributed load balancer");
15
552
}
16
17
using std::vector;
18
19
0
DistributedLB::DistributedLB(CkMigrateMessage *m) : CBase_DistributedLB(m) {
20
0
}
Unexecuted instantiation: _ZN13DistributedLBC2EP16CkMigrateMessage
Unexecuted instantiation: _ZN13DistributedLBC1EP16CkMigrateMessage
21
22
26
DistributedLB::DistributedLB(const CkLBOptions &opt) : CBase_DistributedLB(opt) {
23
26
  lbname = "DistributedLB";
24
26
  if (CkMyPe() == 0 && !quietModeRequested) {
25
8
    CkPrintf("CharmLB> DistributedLB created: threshold %lf, max phases %i\n",
26
8
        kTargetRatio, kMaxPhases);
27
8
  }
28
26
  InitLB(opt);
29
26
}
Unexecuted instantiation: _ZN13DistributedLBC2ERK11CkLBOptions
_ZN13DistributedLBC1ERK11CkLBOptions
Line
Count
Source
22
26
DistributedLB::DistributedLB(const CkLBOptions &opt) : CBase_DistributedLB(opt) {
23
26
  lbname = "DistributedLB";
24
26
  if (CkMyPe() == 0 && !quietModeRequested) {
25
8
    CkPrintf("CharmLB> DistributedLB created: threshold %lf, max phases %i\n",
26
8
        kTargetRatio, kMaxPhases);
27
8
  }
28
26
  InitLB(opt);
29
26
}
30
31
void DistributedLB::initnodeFn()
32
552
{
33
552
  _registerCommandLineOpt("+DistLBTargetRatio");
34
552
  _registerCommandLineOpt("+DistLBMaxPhases");
35
552
}
36
37
26
void DistributedLB::InitLB(const CkLBOptions &opt) {
38
26
  thisProxy = CProxy_DistributedLB(thisgroup);
39
26
  if (opt.getSeqNo() > 0 || (_lb_args.metaLbOn() && _lb_args.metaLbModelDir() != nullptr))
40
0
    turnOff();
41
42
  // Set constants
43
26
  kUseAck = true;
44
26
  kPartialInfoCount = -1;
45
26
  kMaxPhases = _lb_args.maxDistPhases();
46
26
  kTargetRatio = _lb_args.targetRatio();
47
26
}
48
49
207
void DistributedLB::Strategy(const DistBaseLB::LDStats* const stats) {
50
207
  if (CkMyPe() == 0 && _lb_args.debug() >= 1) {
51
46
    start_time = CmiWallTimer();
52
46
    CkPrintf("In DistributedLB strategy at %lf\n", start_time);
53
46
  }
54
55
207
  const int n_objs = stats->objData.size();
56
57
  // Set constants for this iteration (these depend on CkNumPes() or number of
58
  // objects, so may not be constant for the entire program)
59
207
  kMaxObjPickTrials = n_objs;
60
  // Maximum number of times we will try to find a PE to transfer an object
61
  // successfully
62
207
  kMaxTrials = CkNumPes();
63
  // Max gossip messages sent from each PE
64
207
  kMaxGossipMsgCount = 2 * log(CkNumPes())/log(2);
65
66
  // Reset member variables for this LB iteration
67
207
  phase_number = 0;
68
207
  my_stats = stats;
69
70
207
  my_load = 0.0;
71
896
  for (int i = 0; i < n_objs; i++) {
72
689
    my_load += my_stats->objData[i].wallTime; 
73
689
  }
74
207
  init_load = my_load;
75
207
  b_load = my_stats->total_walltime - (my_stats->idletime + my_load);
76
77
207
  pe_no.clear();
78
207
  loads.clear();
79
207
  distribution.clear();
80
207
  lb_started = false;
81
207
  gossip_msg_count = 0;
82
207
  negack_count = 0;
83
84
207
  total_migrates = 0;
85
207
  total_migrates_ack = 0;
86
87
207
  srand((unsigned)(CmiWallTimer()*1.0e06) + CkMyPe());
88
89
  // Do a reduction to obtain load information for the system
90
207
  CkReduction::tupleElement tupleRedn[] = {
91
207
    CkReduction::tupleElement(sizeof(double), &my_load, CkReduction::sum_double),
92
207
    CkReduction::tupleElement(sizeof(double), &my_load, CkReduction::max_double)
93
207
  };
94
207
  CkReductionMsg* msg = CkReductionMsg::buildFromTuple(tupleRedn, 2);
95
207
  CkCallback cb(CkIndex_DistributedLB::LoadReduction(NULL), thisProxy);
96
207
  msg->setCallback(cb);
97
207
  contribute(msg);
98
207
}
99
100
/*
101
* Once the reduction callback is obtained for average load in the system, the
102
* gossiping starts. Only the underloaded processors gossip.
103
* Termination of gossip is via QD and callback is DoneGossip.
104
*/
105
206
void DistributedLB::LoadReduction(CkReductionMsg* redn_msg) {
106
206
  int count;
107
206
  CkReduction::tupleElement* results;
108
206
  redn_msg->toTuple(&results, &count);
109
206
  delete redn_msg;
110
111
  // Set the initial global load stats and print when LBDebug is on
112
206
  avg_load = *(double*)results[0].data / CkNumPes();
113
206
  max_load = *(double*)results[1].data;
114
206
  load_ratio = max_load / avg_load;
115
116
206
  if (CkMyPe() == 0 && _lb_args.debug() >= 1) {
117
46
    CkPrintf("DistributedLB>>>Before LB: max = %lf, avg = %lf, ratio = %lf\n",
118
46
        max_load, avg_load, load_ratio);
119
46
  }
120
121
  // If there are no overloaded processors, immediately terminate
122
206
  if (load_ratio <= kTargetRatio) {
123
146
    if (CkMyPe() == 0 && _lb_args.debug() >= 1) {
124
38
      CkPrintf("DistributedLB>>>Load ratio already within the target of %lf, ending early.\n",
125
38
          kTargetRatio);
126
38
    }
127
146
    PackAndSendMigrateMsgs();
128
146
    delete [] results;
129
146
    return;
130
146
  }
131
132
  // Set transfer threshold for the gossip phase, for which only PEs lower than
133
  // the target ratio are considered underloaded.
134
60
  transfer_threshold = kTargetRatio * avg_load;
135
136
  // If my load is under the acceptance threshold, then I am underloaded and
137
  // can receive more work. So assuming there exists an overloaded PE that can
138
  // donate work, I will start gossipping my load information.
139
60
  if (my_load < transfer_threshold) {
140
34
    underloaded = true;
141
34
    double r_loads[1];
142
34
    int r_pe_no[1];
143
34
    r_loads[0] = my_load;
144
34
    r_pe_no[0] = CkMyPe();
145
34
    GossipLoadInfo(CkMyPe(), 1, r_pe_no, r_loads);
146
34
  } else {
147
26
    underloaded = false;
148
26
  }
149
150
  // Start quiescence detection at PE 0.
151
60
  if (CkMyPe() == 0) {
152
14
    CkCallback cb(CkIndex_DistributedLB::DoneGossip(), thisProxy);
153
14
    CkStartQD(cb);
154
14
  }
155
60
  delete [] results;
156
60
}
157
158
/*
159
* Gossip load information between peers. Receive the gossip message.
160
*/
161
void DistributedLB::GossipLoadInfo(int from_pe, int n,
162
588
    int remote_pe_no[], double remote_loads[]) {
163
  // Placeholder temp vectors for the sorted pe and their load 
164
588
  vector<int> p_no;
165
588
  vector<double> l;
166
167
588
  int i = 0;
168
588
  int j = 0;
169
588
  int m = pe_no.size();
170
171
  // Merge (using merge sort) information received with the information at hand
172
  // Since the initial list is sorted, the merging is linear in the size of the
173
  // list. 
174
1.78k
  while (i < m && j < n) {
175
1.19k
    if (pe_no[i] < remote_pe_no[j]) {
176
91
      p_no.push_back(pe_no[i]);
177
91
      l.push_back(loads[i]);
178
91
      i++;
179
1.10k
    } else {
180
1.10k
      p_no.push_back(remote_pe_no[j]);
181
1.10k
      l.push_back(remote_loads[j]);
182
1.10k
      if (pe_no[i] == remote_pe_no[j]) {
183
1.06k
        i++;
184
1.06k
      }
185
1.10k
      j++;
186
1.10k
    }
187
1.19k
  }
188
189
588
  if (i == m && j != n) {
190
188
    while (j < n) {
191
96
      p_no.push_back(remote_pe_no[j]);
192
96
      l.push_back(remote_loads[j]);
193
96
      j++;
194
96
    }
195
501
  } else if (j == n && i != m) {
196
142
    while (i < m) {
197
77
      p_no.push_back(pe_no[i]);
198
77
      l.push_back(loads[i]);
199
77
      i++;
200
77
    }
201
65
  }
202
203
  // After the merge sort, swap. Now pe_no and loads have updated information
204
588
  pe_no.swap(p_no);
205
588
  loads.swap(l);
206
207
588
  SendLoadInfo();
208
588
}
209
210
/*
211
* Construct the gossip message and send to peers
212
*/
213
585
void DistributedLB::SendLoadInfo() {
214
  // TODO: Keep it 0.8*log
215
  // This PE has already sent the maximum set threshold for gossip messages.
216
  // Hence don't send out any more messages. This is to prevent flooding.
217
585
  if (gossip_msg_count > kMaxGossipMsgCount) {
218
311
    return;
219
311
  }
220
221
  // Pick two random neighbors to send the message to
222
274
  int rand_nbor1;
223
274
  int rand_nbor2 = -1;
224
359
  do {
225
359
    rand_nbor1 = rand() % CkNumPes();
226
359
  } while (rand_nbor1 == CkMyPe());
227
  // Pick the second neighbor which is not the same as the first one.
228
274
  if(CkNumPes() > 2)
229
607
    do {
230
607
      rand_nbor2 = rand() % CkNumPes();
231
607
    } while ((rand_nbor2 == CkMyPe()) || (rand_nbor2 == rand_nbor1));
232
233
  // kPartialInfoCount indicates how much information is send in gossip. If it
234
  // is set to -1, it means use all the information available.
235
274
  int info_count = (kPartialInfoCount >= 0) ? kPartialInfoCount : pe_no.size();
236
274
  int* p = new int[info_count];
237
274
  double* l = new double[info_count];
238
862
  for (int i = 0; i < info_count; i++) {
239
588
    p[i] = pe_no[i];
240
588
    l[i] = loads[i];
241
588
  }
242
243
274
  thisProxy[rand_nbor1].GossipLoadInfo(CkMyPe(), info_count, p, l);
244
245
274
  if(CkNumPes() > 2)
246
279
    thisProxy[rand_nbor2].GossipLoadInfo(CkMyPe(), info_count, p, l);
247
248
  // Increment the outgoind msg count
249
274
  gossip_msg_count++;
250
251
274
  delete[] p;
252
274
  delete[] l;
253
274
}
254
255
/*
256
* Callback invoked when gossip is done and QD is detected
257
*/
258
52
void DistributedLB::DoneGossip() {
259
52
  if (CkMyPe() == 0 && _lb_args.debug() >= 1) {
260
8
    double end_time = CmiWallTimer();
261
8
    CkPrintf("DistributedLB>>>Gossip finished at %lf (%lf elapsed)\n",
262
8
        end_time, end_time - start_time);
263
8
  }
264
  // Set a new transfer threshold for the actual load balancing phase. It starts
265
  // high so that load is initially only transferred from the most loaded PEs.
266
  // In subsequent phases it gets relaxed to allow less overloaded PEs to
267
  // transfer load as well.
268
52
  transfer_threshold = fmax(kTargetRatio * avg_load, (max_load + avg_load) / 2);
269
52
  lb_started = true;
270
52
  underloaded_pe_count = pe_no.size();
271
52
  Setup();
272
52
  StartNextLBPhase();
273
52
}
274
275
131
void DistributedLB::StartNextLBPhase() {
276
131
  if (underloaded_pe_count == 0 || my_load <= transfer_threshold || underloaded) {
277
    // If this PE has no information about underloaded processors, or it has
278
    // no objects to donate to underloaded processors then do nothing.
279
90
    DoneWithLBPhase();
280
90
  } else {
281
    // Otherwise this PE has work to donate, and should attempt to do so.
282
41
    LoadBalance();
283
41
  }
284
131
}
285
286
135
void DistributedLB::DoneWithLBPhase() {
287
135
  phase_number++;
288
289
135
  int count = 1;
290
135
  if (_lb_args.debug() >= 1) count = 3;
291
135
  CkReduction::tupleElement tupleRedn[] = {
292
135
    CkReduction::tupleElement(sizeof(double), &my_load, CkReduction::max_double),
293
135
    CkReduction::tupleElement(sizeof(double), &total_migrates, CkReduction::sum_int),
294
135
    CkReduction::tupleElement(sizeof(double), &negack_count, CkReduction::max_int)
295
135
  };
296
135
  CkReductionMsg* msg = CkReductionMsg::buildFromTuple(tupleRedn, count);
297
135
  CkCallback cb(CkIndex_DistributedLB::AfterLBReduction(NULL), thisProxy);
298
135
  msg->setCallback(cb);
299
135
  contribute(msg);
300
135
}
301
302
136
void DistributedLB::AfterLBReduction(CkReductionMsg* redn_msg) {
303
136
  int count, migrations, max_nacks;
304
136
  CkReduction::tupleElement* results;
305
136
  redn_msg->toTuple(&results, &count);
306
136
  delete redn_msg;
307
308
  // Update load stats and print if in debug mode
309
136
  max_load = *(double*)results[0].data;
310
136
  double old_ratio = load_ratio;
311
136
  load_ratio = max_load / avg_load;
312
136
  if (count > 1) migrations = *(int*)results[1].data;
313
136
  if (count > 2) max_nacks = *(int*)results[2].data;
314
315
136
  if (CkMyPe() == 0 && _lb_args.debug() >= 1) {
316
11
    CkPrintf("DistributedLB>>>After phase %i: max = %lf, avg = %lf, ratio = %lf\n",
317
11
        phase_number, max_load, avg_load, load_ratio);
318
11
  }
319
320
  // Try more phases as long as our load ratio is still worse than our target,
321
  // our transfer threshold hasn't decayed below the target, and we haven't hit
322
  // the maximum number of phases yet.
323
136
  if (load_ratio > kTargetRatio &&
324
136
      transfer_threshold > kTargetRatio * avg_load &&
325
136
      phase_number < kMaxPhases) {
326
    // Relax the transfer ratio to allow more phases based on whether or not the
327
    // previous phase was able to reduce the load ratio at all.
328
81
    if (std::abs(load_ratio - old_ratio) < 0.01) {
329
      // The previous phase didn't meaningfully reduce the max load, so relax
330
      // the transfer threshold.
331
22
      transfer_threshold = fmax(kTargetRatio * avg_load,
332
22
          (transfer_threshold + avg_load) / 2);
333
59
    } else {
334
      // The previous phase did reduce the max load, so update the transfer
335
      // threshold based on the new max load.
336
59
      transfer_threshold = fmax(kTargetRatio * avg_load,
337
59
          (max_load + avg_load) / 2);
338
59
    }
339
81
    StartNextLBPhase();
340
81
  } else {
341
55
    if (CkMyPe() == 0 && _lb_args.debug() >= 1) {
342
8
      double end_time = CmiWallTimer();
343
8
      CkPrintf("DistributedLB>>>Balancing completed at %lf (%lf elapsed)\n",
344
8
          end_time, end_time - start_time);
345
8
      CkPrintf("DistributedLB>>>%i total migrations with %i negative ack max\n",
346
8
          migrations, max_nacks);
347
8
    }
348
55
    Cleanup();
349
55
    PackAndSendMigrateMsgs();
350
55
    if (!(_lb_args.metaLbOn() && _lb_args.metaLbModelDir() != nullptr))
351
55
      lbmgr->nextLoadbalancer(seqno);
352
55
  }
353
136
  delete [] results;
354
136
}
355
356
/*
357
* Perform load balancing based on the partial information obtained from the
358
* information propagation stage (gossip).
359
*/
360
45
void DistributedLB::LoadBalance() {
361
45
  vector<int> obj_no;
362
45
  vector<int> obj_pe_no;
363
364
  // Balance load and add objs to be transferred to obj_no and pe to be
365
  // transferred to in obj_pe_no
366
45
  MapObjsToPe(objs, obj_no, obj_pe_no);
367
45
  total_migrates += obj_no.size();
368
45
  total_migrates_ack = obj_no.size();
369
370
  // If there is no migration, then this is done
371
45
  if (obj_no.empty()) {
372
10
    DoneWithLBPhase();
373
10
  }
374
45
}
375
376
53
void DistributedLB::Setup() {
377
53
  objs_count = 0;
378
53
  double avg_objload = 0.0;
379
53
  double max_objload = 0.0;
380
  // Count the number of objs that are migratable and whose load is not 0.
381
53
  const int n_objs = my_stats->objData.size();
382
469
  for(int i=0; i < n_objs; i++) {
383
416
    if (my_stats->objData[i].migratable &&
384
416
      my_stats->objData[i].wallTime > 0.000001) {
385
390
      objs_count++;
386
390
    }
387
416
  }
388
 
389
  // Create a min heap of objs. The idea is to transfer smaller objs. The reason
390
  // is that since we are making probabilistic transfer of load, sending small
391
  // objs will result in better load balance.
392
53
  objs = new minHeap(objs_count);
393
483
  for(int i=0; i < n_objs; i++) {
394
430
    if (my_stats->objData[i].migratable &&
395
430
        my_stats->objData[i].wallTime > 0.0001) {
396
409
      InfoRecord* item = new InfoRecord;
397
409
      item->load = my_stats->objData[i].wallTime;
398
409
      item->Id = i;
399
409
      objs->insert(item);
400
409
    }
401
430
  }
402
403
  // Calculate the probabilities and cdf for PEs based on their load
404
  // distribution
405
53
  CalculateCumulateDistribution();
406
53
}
407
408
53
void DistributedLB::Cleanup() {
409
410
  // Delete the object records from the heap
411
53
  InfoRecord* obj;
412
283
  while (NULL!=(obj=objs->deleteMin())) {
413
230
    delete obj;
414
230
  }
415
53
  delete objs;
416
53
}
417
418
/*
419
* Map objects to PE for load balance. It takes in a min heap of objects which
420
* can be transferred and finds suitable receiver PEs. The mapping is stored in
421
* obj_no and the corresponding entry in obj_pe_no indicates the receiver PE.
422
*/
423
void DistributedLB::MapObjsToPe(minHeap *objs, vector<int> &obj_no,
424
46
                                vector<int> &obj_pe_no) {
425
46
  int p_id;
426
46
  double p_load;
427
46
  int rand_pe;
428
429
  // While my load is more than the threshold, try to transfer objs
430
214
  while (my_load > transfer_threshold) {
431
    // If there is only one object, then nothing can be done to balance it.
432
181
    if (objs_count < 2) break;
433
434
    // Flag to indicate whether successful in finding a transfer
435
177
    bool success = false;
436
437
    // Get the smallest object
438
177
    InfoRecord* obj = objs->deleteMin();
439
    // No more objects to retrieve
440
177
    if (obj == 0) break;
441
442
    // Pick random PE based on the probability and the find is successful only
443
    // if on transferring the object, that PE does not become overloaded
444
187
    do {
445
187
      rand_pe = PickRandReceiverPeIdx();
446
187
      if (rand_pe == -1) break;
447
187
      p_id = pe_no[rand_pe];
448
187
      p_load = loads[rand_pe];
449
187
      if (p_load + obj->load < transfer_threshold) {
450
168
        success = true;
451
168
      }
452
187
      kMaxTrials--;
453
187
    } while (!success && (kMaxTrials > 0));
454
455
177
    kMaxObjPickTrials--;
456
457
    // No successful in finding a suitable PE to transfer the object
458
177
    if (!success) {
459
9
      objs->insert(obj);
460
9
      break;
461
9
    }
462
463
    // Found an object and a suitable PE to transfer it to. Decrement the obj
464
    // count and update the loads.
465
168
    obj_no.push_back(obj->Id);
466
168
    obj_pe_no.push_back(p_id);
467
168
    objs_count--;
468
168
    loads[rand_pe] += obj->load;
469
168
    my_load -= obj->load;
470
471
    // Send information to the receiver PE about this obj. This is necessary for
472
    // ack as well as finding out how many objs are migrating in
473
168
    thisProxy[p_id].InformMigration(obj->Id, CkMyPe(),
474
168
        my_stats->objData[obj->Id].wallTime, false);
475
476
    // This object is assigned, so we delete it from the heap
477
168
    delete obj;
478
168
  }
479
46
}
480
481
/*
482
* Receive information about inbound object including the id, from_pe and its
483
* load. 
484
*
485
* obj_id is the index of the object in the original PE.
486
* from_pe is the originating PE
487
* obj_load is the load of this object
488
* force flag indicates that this PE is forced to accept the object after
489
* multiple trials and ack should not be sent.
490
*/
491
void DistributedLB::InformMigration(int obj_id, int from_pe, double obj_load,
492
166
    bool force) {
493
  // If not using ack based scheme or adding this obj does not make this PE
494
  // overloaded, then accept the migrated obj and return. 
495
166
  if (!kUseAck || my_load + obj_load <= transfer_threshold) {
496
164
    migrates_expected++;
497
    // add to my load and reply true
498
164
    my_load += obj_load;
499
164
    thisProxy[from_pe].RecvAck(obj_id, CkMyPe(), true);
500
164
    return;
501
164
  }
502
503
  // We are using ack based scheme and turns out accepting this obj will make me
504
  // overloaded but if it is a forced one, then accept it else return negative
505
  // acknowledgement.
506
2
  if (force) {
507
0
    migrates_expected++;
508
    // add to my load and reply with positive ack
509
0
    my_load += obj_load;
510
2
  } else {
511
    // If my_load + obj_load is > threshold, then reply with negative ack 
512
    //CkPrintf("[%d] Cannot accept obj with load %lf my_load %lf and init_load %lf migrates_expected %d\n", CkMyPe(), obj_load, my_load, init_load, migrates_expected);
513
2
    thisProxy[from_pe].RecvAck(obj_id, CkMyPe(), false);
514
2
  }
515
2
}
516
517
/*
518
* Receive an ack message which the message whether the assigned object can be
519
* assigned or not. If all the acks have been received, then create migration
520
* message.
521
*/
522
169
void DistributedLB::RecvAck(int obj_id, int assigned_pe, bool can_accept) {
523
169
  total_migrates_ack--;
524
525
  // If it is a positive ack, then create a migrate msg for that object
526
169
  if (can_accept) {
527
167
    MigrateInfo* migrateMe = new MigrateInfo;
528
167
    migrateMe->obj = my_stats->objData[obj_id].handle;
529
167
    migrateMe->from_pe = CkMyPe();
530
167
    migrateMe->to_pe = assigned_pe;
531
167
    migrateInfo.push_back(migrateMe);
532
167
  } else if (negack_count > 0.01*underloaded_pe_count) {
533
    // If received negative acks more than the specified threshold, then drop it
534
0
    negack_count++;
535
0
    total_migrates--;
536
0
    objs_count++;
537
0
    my_load += my_stats->objData[obj_id].wallTime;
538
2
  } else {
539
    // Try to transfer again. Add the object back to a heap, update my load and
540
    // try to find a suitable PE now.
541
2
    total_migrates--;
542
2
    negack_count++;
543
2
    objs_count++;
544
2
    my_load += my_stats->objData[obj_id].wallTime;
545
546
2
    minHeap* objs = new minHeap(1);
547
2
    InfoRecord* item = new InfoRecord;
548
2
    item->load = my_stats->objData[obj_id].wallTime;
549
2
    item->Id = obj_id;
550
2
    objs->insert(item);
551
552
2
    vector<int> obj_no;
553
2
    vector<int> obj_pe_no;
554
2
    MapObjsToPe(objs, obj_no, obj_pe_no);
555
556
    // If a PE could be found to transfer this object, MapObjsToPe sends a
557
    // message to it. Wait for the ack.
558
    // Maybe at this point we can try to force it or just drop it.
559
2
    if (!obj_pe_no.empty()) {
560
0
      total_migrates_ack++;
561
0
      total_migrates++;
562
0
    }
563
2
    InfoRecord* obj;
564
4
    while (NULL!=(obj=objs->deleteMin())) {
565
2
      delete obj;
566
2
    }
567
2
  }
568
569
  // Whenever all the acks have been received, create migration msg, go into the
570
  // barrier and wait for everyone to finish their load balancing phase
571
169
  if (total_migrates_ack == 0) {
572
35
    DoneWithLBPhase();
573
35
  }
574
169
}
575
576
200
void DistributedLB::PackAndSendMigrateMsgs() {
577
200
  LBMigrateMsg* msg = new(total_migrates,CkNumPes(),CkNumPes(),0) LBMigrateMsg;
578
200
  msg->n_moves = total_migrates;
579
367
  for(int i=0; i < total_migrates; i++) {
580
167
    MigrateInfo* item = (MigrateInfo*) migrateInfo[i];
581
167
    msg->moves[i] = *item;
582
167
    delete item;
583
167
    migrateInfo[i] = 0;
584
167
  }
585
200
  migrateInfo.clear();
586
200
  ProcessMigrationDecision(msg);
587
200
}
588
589
/*
590
* Pick a random PE based on the probability distribution.
591
*/
592
188
int DistributedLB::PickRandReceiverPeIdx() const {
593
  // The min loaded PEs have probabilities inversely proportional to their load.
594
  // A cumulative distribution is calculated and a PE is randomly selected based
595
  // on the cdf.
596
  // Generate a random number and return the index of min loaded PE whose cdf is
597
  // greater than the random number.
598
188
  double no = (double) rand()/(double) RAND_MAX;
599
357
  for (int i = 0; i < underloaded_pe_count; i++) {
600
356
    if (distribution[i] >= no) {
601
187
      return i;
602
187
    }
603
356
  }
604
1
  return -1;
605
188
}
606
607
/*
608
* The PEs have probabilities inversely proportional to their load. Construct a
609
* CDF based on this.
610
*/
611
53
void DistributedLB::CalculateCumulateDistribution() {
612
  // The min loaded PEs have probabilities inversely proportional to their load.
613
53
  double cumulative = 0.0;
614
185
  for (int i = 0; i < underloaded_pe_count; i++) {
615
132
    cumulative += (transfer_threshold - loads[i])/transfer_threshold;
616
132
    distribution.push_back(cumulative);
617
132
  }
618
619
184
  for (int i = 0; i < underloaded_pe_count; i++) {
620
131
    distribution[i] = distribution[i]/cumulative;
621
131
  }
622
53
}
623
624
#include "DistributedLB.def.h"