parallel_for_ex.cpp 7.75 KB
Newer Older
1
2
3
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*

Davis King's avatar
Davis King committed
4
5
6
7
    This is an example illustrating the use of the parallel for loop tools from the dlib
    C++ Library.

    Normally, a for loop executes the body of the loop in a serial manner.  This means
Davis King's avatar
Davis King committed
8
9
    that, for example, if it takes 1 second to execute the body of the loop and the body
    needs to execute 10 times then it will take 10 seconds to execute the entire loop.
Davis King's avatar
Davis King committed
10
11
12
    However, on modern multi-core computers we have the opportunity to speed this up by
    executing multiple steps of a for loop in parallel.  This example program will walk you
    though a few examples showing how to do just that.  
13
14
15
16
17
18
19
20
21
22
23
*/


#include <dlib/threads.h>
#include <dlib/misc_api.h>  // for dlib::sleep
#include <vector>
#include <iostream>

using namespace dlib;
using namespace std;

Davis King's avatar
Davis King committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// ----------------------------------------------------------------------------------------

void print(const std::vector<int>& vect)
{
    for (unsigned long i = 0; i < vect.size(); ++i)
    {
        cout << vect[i] << endl;
    }
    cout << "\n**************************************\n";
}

// ----------------------------------------------------------------------------------------

void example_using_regular_non_parallel_loops();
void example_using_lambda_functions();
void example_without_using_lambda_functions();

// ----------------------------------------------------------------------------------------

int main()
{
    // We have 3 examples, each contained in a separate function.  Each example performs
Davis King's avatar
Davis King committed
46
47
    // exactly the same computation, however, the second two examples do so using parallel
    // for loops.  So the first example is here to show you what we are doing in terms of
Davis King's avatar
Davis King committed
48
    // classical non-parallel for loops.  Then the next two examples will illustrate two
Davis King's avatar
Davis King committed
49
50
51
    // ways to parallelize for loops in C++.  The first, and simplest way, uses C++11
    // lambda functions.  However, since lambda functions are a relatively recent addition
    // to C++ we also show how to write parallel for loops without using lambda functions.
Davis King's avatar
Davis King committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    // This way, users who don't yet have access to a current C++ compiler can learn to
    // write parallel for loops as well.

    example_using_regular_non_parallel_loops();
    example_using_lambda_functions();
    example_without_using_lambda_functions();
}

// ----------------------------------------------------------------------------------------

void example_using_regular_non_parallel_loops()
{
    cout << "\nExample using regular non-parallel for loops\n" << endl;

    std::vector<int> vect;

    // put 10 elements into vect which are all equal to -1
    vect.assign(10, -1);

    // Now set each element equal to its index value.  We put a sleep call in here so that
    // when we run the same thing with a parallel for loop later on you will be able to
    // observe the speedup. 
    for (unsigned long i = 0; i < vect.size(); ++i)
    {
        vect[i] = i;
        dlib::sleep(1000); // sleep for 1 second
    }
    print(vect);



Davis King's avatar
Davis King committed
83
    // Assign only part of the elements in vect.
Davis King's avatar
Davis King committed
84
85
86
87
88
89
90
91
92
93
    vect.assign(10, -1);
    for (unsigned long i = 1; i < 5; ++i)
    {
        vect[i] = i;
        dlib::sleep(1000);
    }
    print(vect);



Davis King's avatar
Davis King committed
94
    // Sum all element sin vect.
Davis King's avatar
Davis King committed
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    int sum = 0;
    vect.assign(10, 2);
    for (unsigned long i = 0; i < vect.size(); ++i)
    {
        dlib::sleep(1000);
        sum += vect[i];
    }

    cout << "sum: "<< sum << endl;
}

// ----------------------------------------------------------------------------------------

void example_using_lambda_functions()
{
// Change the next line to #if 1 if your compiler supports the new C++11 lambda functions. 
#if 0
    cout << "\nExample using parallel for loops\n" << endl;

    // This variable should be set to the number of processing cores on your computer since
    // it determines the amount of parallelism in the for loop.  
    const unsigned long num_threads = 10;

    std::vector<int> vect;

    vect.assign(10, -1);
    parallel_for(num_threads, 0, vect.size(), [&](long i){
        // The i variable is the loop counter as in a normal for loop.  So we simply need
Davis King's avatar
Davis King committed
123
        // to place the body of the for loop right here and we get the same behavior.  The
Davis King's avatar
Davis King committed
124
125
126
127
128
129
130
131
        // range for the for loop is determined by the 2nd and 3rd arguments to
        // parallel_for().
        vect[i] = i;
        dlib::sleep(1000);
    });
    print(vect);


Davis King's avatar
Davis King committed
132
    // Assign only part of the elements in vect.
Davis King's avatar
Davis King committed
133
134
135
136
137
138
139
140
141
142
143
144
    vect.assign(10, -1);
    parallel_for(num_threads, 1, 5, [&](long i){
        vect[i] = i;
        dlib::sleep(1000);
    });
    print(vect);


    // Note that things become a little more complex if the loop bodies are not totally
    // independent.  In the first two cases each iteration of the loop touched different
    // memory locations, so we didn't need to use any kind of thread synchronization.
    // However, in the summing loop we need to add some synchronization to protect the sum
Davis King's avatar
Davis King committed
145
    // variable.  This is easily accomplished by creating a mutex and locking it before
Davis King's avatar
Davis King committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    // adding to sum.  More generally, you must ensure that the bodies of your parallel for
    // loops are thread safe using whatever means is appropriate for your code.  Since a
    // parallel for loop is implemented using threads, all the usual techniques for
    // ensuring thread safety can be used. 
    int sum = 0;
    mutex m;
    vect.assign(10, 2);
    parallel_for(num_threads, 0, vect.size(), [&](long i){
        // The sleep statements still execute in parallel.  
        dlib::sleep(1000);

        // Lock the m mutex.  The auto_mutex will automatically unlock at the closing }.
        // This will ensure only one thread can execute the sum += vect[i] statement at
        // a time.
        auto_mutex lock(m);
        sum += vect[i];
    });

    cout << "sum: "<< sum << endl;

#endif
}

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
//    The rest of this example program shows how to create parallel for loops without
//    using lambda functions.  So the first thing we do is explicitly create function
//    objects equivalent to the lambda functions we used.  Then we call parallel_for() 
//    as done above.
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

178
179
struct function_object
{
Davis King's avatar
Davis King committed
180
    function_object( std::vector<int>& vect ) : vect(vect) {}
181

Davis King's avatar
Davis King committed
182
    std::vector<int>& vect;
183
184
185

    void operator() (long i) const
    {
Davis King's avatar
Davis King committed
186
187
        vect[i] = i;
        dlib::sleep(1000); 
188
189
190
    }
};

Davis King's avatar
Davis King committed
191
struct function_object_sum
192
{
Davis King's avatar
Davis King committed
193
    function_object_sum( const std::vector<int>& vect, int& sum_ ) : vect(vect), sum(sum_) {}
194

Davis King's avatar
Davis King committed
195
196
197
    const std::vector<int>& vect;
    int& sum;
    mutex m;
198

Davis King's avatar
Davis King committed
199
200
201
202
203
204
205
    void operator() (long i) const
    {
        dlib::sleep(1000); 
        auto_mutex lock(m);
        sum += vect[i];
    }
};
206

Davis King's avatar
Davis King committed
207
208
209
210
void example_without_using_lambda_functions()
{
    // Again, note that this function does exactly the same thing as
    // example_using_regular_non_parallel_loops() and example_using_lambda_functions().
211

Davis King's avatar
Davis King committed
212
    cout << "\nExample using parallel for loops and no lambda functions\n" << endl;
213

Davis King's avatar
Davis King committed
214
215
    const unsigned long num_threads = 10;
    std::vector<int> vect;
216
217


Davis King's avatar
Davis King committed
218
219
220
    vect.assign(10, -1); 
    parallel_for(num_threads, 0, vect.size(), function_object(vect));
    print(vect);
221
222


Davis King's avatar
Davis King committed
223
224
225
    vect.assign(10, -1);
    parallel_for(num_threads, 1, 5, function_object(vect));
    print(vect);
226
227


Davis King's avatar
Davis King committed
228
229
230
231
232
    int sum = 0;
    vect.assign(10, 2);
    parallel_for(num_threads, 0, vect.size(), function_object_sum(vect, sum));
    cout << "sum: " << sum << endl;
}
233

Davis King's avatar
Davis King committed
234
// ----------------------------------------------------------------------------------------
235