Skip to content

Commit 709f787

Browse files
fixed parallel_for bug and added unittest
1 parent cfa75f4 commit 709f787

File tree

4 files changed

+40
-3
lines changed

4 files changed

+40
-3
lines changed

CMakeLists.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,9 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/unittest)
7979
add_executable(taskflow unittest/taskflow.cpp)
8080
target_link_libraries(taskflow Threads::Threads)
8181

82-
add_test(unittest ${PROJECT_SOURCE_DIR}/unittest/taskflow)
82+
add_test(builder ${PROJECT_SOURCE_DIR}/unittest/taskflow -tc=Taskflow.Builder)
83+
add_test(dispatch ${PROJECT_SOURCE_DIR}/unittest/taskflow -tc=Taskflow.Dispatch)
84+
add_test(parallel_for ${PROJECT_SOURCE_DIR}/unittest/taskflow -tc=Taskflow.ParallelFor)
8385

8486

8587

example/parallel_for.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "taskflow.hpp"
2+
#include <cassert>
23

34
// Function: fib
45
int fib(int n) {
@@ -28,7 +29,7 @@ void taskflow(int N) {
2829
for(int n=0; n<N; ++n) {
2930
range[n] = n;
3031
}
31-
tf.parallel_for(range.begin(), range.end(), [&] (int& i) {
32+
tf.parallel_for(range.begin(), range.end(), [&range] (int& i) {
3233
printf("fib[%d]=%d\n", i, fib(i));
3334
});
3435
tf.wait_for_all();

taskflow.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -815,7 +815,7 @@ auto BasicTaskflow<F>::parallel_for(I beg, I end, C&& c) {
815815
auto target = placeholder();
816816

817817
for(; beg != end; ++beg) {
818-
auto task = silent_emplace([&, itr=beg] (){ c(*itr); });
818+
auto task = silent_emplace([c, itr=beg] (){ c(*itr); });
819819
source.precede(task);
820820
task.precede(target);
821821
}

unittest/taskflow.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,40 @@ TEST_CASE("Taskflow.Dispatch") {
198198
}
199199
}
200200

201+
// --------------------------------------------------------
202+
// Testcase: Taskflow.ParallelFor
203+
// --------------------------------------------------------
204+
TEST_CASE("Taskflow.ParallelFor") {
205+
206+
using namespace std::chrono_literals;
207+
208+
std::vector<int> vec(1024, 0);
209+
210+
tf::Taskflow tf;
211+
212+
// map
213+
SUBCASE("Map") {
214+
tf.parallel_for(vec.begin(), vec.end(), [] (int& v) { v = 64; });
215+
for(const auto v : vec) {
216+
REQUIRE(v == 0);
217+
}
218+
tf.wait_for_all();
219+
for(const auto v : vec) {
220+
REQUIRE(v == 64);
221+
}
222+
}
223+
224+
// reduce
225+
SUBCASE("Reduce") {
226+
std::atomic<int> sum(0);
227+
tf.parallel_for(vec.begin(), vec.end(), [&](auto) { ++sum; });
228+
REQUIRE(sum == 0);
229+
tf.wait_for_all();
230+
REQUIRE(sum == vec.size());
231+
}
232+
}
233+
234+
201235

202236

203237

0 commit comments

Comments
 (0)