Skip to content

Commit

Permalink
revised figure 3-1 code
Browse files Browse the repository at this point in the history
  • Loading branch information
James Reinders committed Dec 2, 2024
1 parent 3d46081 commit bcab38f
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 28 deletions.
49 changes: 39 additions & 10 deletions new_examples/containers/pop_danger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,54 @@

#include <iostream>
#include <queue>
#include <tbb/parallel_invoke.h>

int main() {
int sum (0);
int item;
int sum0(0), sum1(0);

std::priority_queue<int> myPQ;

for(int i=0; i<10001; i+=1) {
myPQ.push(i);
}

while( !myPQ.empty() ) {
sum += myPQ.top();
myPQ.pop();
}

tbb::parallel_invoke(
[&]() {
while( !myPQ.empty() ) {
sum0 += myPQ.top();
myPQ.pop();
}
},
[&]() {
while( !myPQ.empty() ) {
sum1 += myPQ.top();
myPQ.pop();
}
});

// prints "total: 50005000" (for 0,10001,1)
// if correct (which it is not) this
// would print "total: 50005000" (for 0,10001,1)
std::cout << "total: "
<< sum << '\n';

<< sum0+sum1 << '\n';
return 0;
}

//
// Sample outputs:
// % ./pop_danger
// total: 128379594
// % ./pop_danger
// total: 124432912
// % ./pop_danger
// total: 107697942
// % ./pop_danger
// total: 50005000
// % ./pop_danger
// total: 115224669
// % ./pop_danger
// total: 146790135
// % ./pop_danger
// total: 130683763
// % ./pop_danger
// total: 126960607
//
39 changes: 21 additions & 18 deletions new_examples/containers/pop_danger_fixed.cpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
/*
Copyright (c) 2024 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand All @@ -15,26 +12,32 @@
*/

#include <iostream>

#include <tbb/concurrent_priority_queue.h>
#include <tbb/parallel_invoke.h>
#include <tbb/parallel_for.h>


int main() {
int sum (0);
int item = 0;

tbb::concurrent_priority_queue<int> myPQ;

tbb::parallel_for(0,10001,1,
[&](size_t i){myPQ.push(i);} );

while( myPQ.try_pop(item) )
sum += item;
int main() {
int sum0(0), sum1(0);

tbb::concurrent_priority_queue<int> myPQ;

tbb::parallel_for(0,10001,1,
[&](size_t i){ myPQ.push(i); } );

tbb::parallel_invoke(
[&]() {
int item = 0;
while( myPQ.try_pop(item) )
sum0 += item;
},
[&]() {
int item = 0;
while( myPQ.try_pop(item) )
sum1 += item;
});

// prints "total: 50005000" (for 0,10001,1)
std::cout << "total: "
<< sum << '\n';

<< sum0+sum1 << '\n';
return 0;
}

0 comments on commit bcab38f

Please sign in to comment.