source: trunk/user/sort/sort.c @ 654

Last change on this file since 654 was 652, checked in by alain, 5 years ago

Introduce the three placement modes in "transpose", "convol', "fft" applications.

  • Property svn:executable set to *
File size: 13.8 KB
Line 
1/*
2 * sort.c - Parallel sort
3 *
4 * Author     Cesar Fuguet Tortolero (2013)
5 *            Alain Greiner (2019)
6 *
7 * Copyright (c) UPMC Sorbonne Universites
8 *
9 * This is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; version 2.0 of the License.
12 *
13 * It is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with ALMOS-MKH; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23///////////////////////////////////////////////////////////////////////////////
24// This multi-threaded application implement a multi-stage sort.
25// It has been writen by Cesar Fuget Tortolero in 2013.
26// It has been ported on ALMOS-MKH by Alain Greiner in 2019.
27//
28// There is one thread per physical cores.
29// Computation is organised as a binary tree:
30// - All threads execute in parallel a buble sort on a sub-array during the
31//   the first stage of parallel sort,
32// - The number of participating threads is divided by 2 at each next stage,
33//   to make a merge sort, on two subsets of previous stage.
34//
35//       Number_of_stages = number of barriers = log2(Number_of_threads)
36//
37// The various stages are separated by synchronisation barriers, and the
38// main thread uses the join syscall to check that all threads completed
39// before printing the computation time (sequencial & parallel).
40// These results can be - optionnaly - registered in an instrumentation file.
41//
42// Constraints :
43// - It supports up to 1024 cores: x_size, y_size, and ncores must be
44//   power of 2 (max 16*16 clusters / max 4 cores per cluster)
45// _ The array of values to be sorted (ARRAY_LENGTH) must be power of 2
46//   larger than the number of cores.
47///////////////////////////////////////////////////////////////////////////////
48
49#include <stdio.h>
50#include <stdlib.h>
51#include <unistd.h>
52#include <pthread.h>
53#include <almosmkh.h>
54#include <hal_macros.h>
55
56#define ARRAY_LENGTH        2048            // number of items
57#define MAX_THREADS         1024            // 16 * 16 * 4
58
59#define X_MAX               16              // max number of clusters in a row
60#define Y_MAX               16              // max number of clusters in a column
61#define CORES_MAX           4               // max number of cores in a cluster
62#define CLUSTERS_MAX        X_MAX * Y_MAX
63
64#define USE_DQT_BARRIER     1               // use DQT barrier if non zero
65#define DISPLAY_ARRAY       0               // display items values before and after
66#define DEBUG_MAIN          0               // trace main function
67#define DEBUG_SORT          0               // trace sort function
68#define CHECK_RESULT        0               // for debug
69#define INSTRUMENTATION     1               // register computation times on file
70
71////////////////////////////////////////////////////////////////////////////////////
72//            Sort specific global variables
73////////////////////////////////////////////////////////////////////////////////////
74
75int                 array0[ARRAY_LENGTH];    // values to sort
76int                 array1[ARRAY_LENGTH];   
77
78unsigned int        threads;                // total number of working threads
79
80pthread_barrier_t   barrier;                 // synchronisation variables
81
82/////////////////////////////////////////////////////////////////////////////////////
83//             Global variables required by parallel_pthread_create()
84/////////////////////////////////////////////////////////////////////////////////////
85
86
87////////////////////////////////////
88static void bubbleSort( int * array,
89                        unsigned int length,
90                        unsigned int init_pos )
91{
92    unsigned int i;
93    unsigned int j;
94    int          aux;
95
96    for(i = 0; i < length; i++)
97    {
98        for(j = init_pos; j < (init_pos + length - i - 1); j++)
99        {
100            if(array[j] > array[j + 1])
101            {
102                aux          = array[j + 1];
103                array[j + 1] = array[j];
104                array[j]     = aux;
105            }
106        }
107    }
108}  // end bubbleSort()
109
110
111///////////////////////////////////
112static void merge( const int * src,               // source array
113                   int       * dst,               // destination array
114                   int         length,            // number of items in a subset
115                   int         init_pos_src_a,    // index first item in src subset A
116                   int         init_pos_src_b,    // index first item in src subset B
117                   int         init_pos_dst )     // index first item in destination
118{
119    int i;
120    int j;
121    int k;
122
123    i = 0;
124    j = 0;
125    k = init_pos_dst;
126
127    while((i < length) || (j < length))
128    {
129        if((i < length) && (j < length))
130        {
131            if(src[init_pos_src_a + i] < src[init_pos_src_b + j])
132            {
133                dst[k++] = src[init_pos_src_a + i];
134                i++;
135            }
136            else
137            {
138                dst[k++] = src[init_pos_src_b + j];
139                j++;
140            }
141        }
142        else if(i < length)
143        {
144            dst[k++] = src[init_pos_src_a + i];
145            i++;
146        }
147        else
148        {
149            dst[k++] = src[init_pos_src_b + j];
150            j++;
151        }
152    }
153}  // end merge()
154
155///////////////////////////////////////////////
156void sort( pthread_parallel_work_args_t * ptr )
157{
158    unsigned int        i;
159    int               * src_array  = NULL;
160    int               * dst_array  = NULL;
161
162    // get arguments
163    unsigned int        tid            = ptr->tid;
164    pthread_barrier_t * parent_barrier = ptr->barrier;
165
166    unsigned int        items      = ARRAY_LENGTH / threads;
167    unsigned int        stages     = __builtin_ctz( threads ) + 1;
168
169#if DEBUG_SORT
170printf("\n[sort] start : ptr %x / tid %d / threads %d / parent_barrier %x\n",
171ptr, tid, threads, parent_barrier );
172#endif
173
174    bubbleSort( array0, items, items * tid );
175
176#if DEBUG_SORT
177printf("\n[sort] thread[%d] : stage 0 completed\n", tid );
178#endif
179
180    /////////////////////////////////
181    pthread_barrier_wait( &barrier ); 
182
183#if DEBUG_SORT
184printf("\n[sort] thread[%d] exit barrier 0\n", tid );
185#endif
186
187    // the number of threads contributing to sort is divided by 2
188    // and the number of items is multiplied by 2 at each next stage
189    for ( i = 1 ; i < stages ; i++ )
190    {
191        if((i % 2) == 1)               // odd stage
192        {
193            src_array = array0;
194            dst_array = array1;
195        }
196        else                           // even stage
197        {
198            src_array = array1;
199            dst_array = array0;
200        }
201
202        if( (tid & ((1<<i)-1)) == 0 )
203        {
204
205#if DEBUG_SORT
206printf("\n[sort] thread[%d] : stage %d start\n", tid , i );
207#endif
208            merge( src_array, 
209                   dst_array,
210                   items << (i-1),
211                   items * tid,
212                   items * (tid + (1 << (i-1))),
213                   items * tid );
214
215#if DEBUG_SORT
216printf("\n[sort] thread[%d] : stage %d completed\n", tid , i );
217#endif
218        }
219
220        /////////////////////////////////
221        pthread_barrier_wait( &barrier );
222
223#if DEBUG_SORT
224printf("\n[sort] thread[%d] exit barrier %d\n", tid , i );
225#endif
226
227    }  // en for stages
228
229    // sort thread signal completion to pthtread_parallel_create()
230    pthread_barrier_wait( parent_barrier );
231
232#if DEBUG_SORT
233printf("\n[sort] thread[%d] exit\n", tid );
234#endif
235
236    // sort thread exit
237    pthread_exit( NULL );
238
239} // end sort()
240
241
242/////////////////
243void main( void )
244{
245    int                    error;
246    unsigned int           x_size;             // number of rows
247    unsigned int           y_size;             // number of columns
248    unsigned int           ncores;             // number of cores per cluster
249    pthread_barrierattr_t  barrier_attr;       // barrier attributes (used for DQT)
250    unsigned int           n;                  // index in array to sort
251
252    unsigned long long     start_cycle;
253    unsigned long long     seq_end_cycle;
254    unsigned long long     para_end_cycle;
255
256    /////////////////////////
257    get_cycle( &start_cycle );
258 
259    // compute number of working threads (one thread per core)
260    get_config( &x_size , &y_size , &ncores );
261    threads = x_size * y_size * ncores;
262
263    // compute covering DQT size an level
264    unsigned int z = (x_size > y_size) ? x_size : y_size;
265    unsigned int root_level = (z == 1) ? 0 : (z == 2) ? 1 : (z == 4) ? 2 : (z == 8) ? 3 : 4;
266
267    // checks number of threads
268    if ( (threads != 1)   && (threads != 2)   && (threads != 4)   && 
269         (threads != 8)   && (threads != 16 ) && (threads != 32)  && 
270         (threads != 64)  && (threads != 128) && (threads != 256) && 
271         (threads != 512) && (threads != 1024) )
272    {
273        printf("\n[sort] ERROR : number of cores must be power of 2\n");
274        exit( 0 );
275    }
276
277    // check array size
278    if ( ARRAY_LENGTH % threads) 
279    {
280        printf("\n[sort] ERROR : array size must be multiple of number of threads\n");
281        exit( 0 );
282    }
283
284    printf("\n[sort] main starts / %d threads / %d items / pid %x / cycle %d\n",
285    threads, ARRAY_LENGTH, getpid(), (unsigned int)start_cycle );
286
287    // initialize barrier
288    if( USE_DQT_BARRIER )
289    {
290        barrier_attr.x_size   = x_size; 
291        barrier_attr.y_size   = y_size;
292        barrier_attr.nthreads = ncores;
293        error = pthread_barrier_init( &barrier, &barrier_attr , threads );
294    }
295    else // use SIMPLE_BARRIER
296    {
297        error = pthread_barrier_init( &barrier, NULL , threads );
298    }
299
300    if( error )
301    {
302        printf("\n[sort] ERROR : cannot initialise barrier\n" );
303        exit( 0 );
304    }
305
306#if DEBUG_MAIN
307if( USE_DQT_BARRIER ) printf("\n[sort] main completes DQT barrier init\n");
308else                  printf("\n[sort] main completes simple barrier init\n");
309#endif
310
311    // Array to sort initialization
312    for ( n = 0 ; n < ARRAY_LENGTH ; n++ )
313    {
314        array0[n] = ARRAY_LENGTH - n - 1;
315    }
316
317#if DISPLAY_ARRAY
318    printf("\n*** array before sort\n");
319    for( n=0; n<ARRAY_LENGTH; n++) printf("array[%d] = %d\n", n , array0[n] );
320#endif
321
322#if DEBUG_MAIN
323printf("\n[sort] main completes array init\n");
324#endif
325
326    ///////////////////////////
327    get_cycle( &seq_end_cycle );
328
329#if DEBUG_MAIN
330printf("\n[sort] main completes sequencial init at cycle %d\n",
331(unsigned int)seq_end_cycle );
332#endif
333
334    // create and execute the working threads
335    if( pthread_parallel_create( root_level,
336                                 &sort ) )
337    {
338        printf("\n[sort] ERROR : cannot create threads\n");
339        exit( 0 );
340    }
341
342    ////////////////////////////
343    get_cycle( &para_end_cycle );
344
345#if DEBUG_main
346printf("\n[sort] main completes parallel sort at cycle %d\n", 
347(unsigned int)para_end_cycle );
348#endif
349
350    // destroy barrier
351    pthread_barrier_destroy( &barrier );
352
353#if DISPLAY_ARRAY
354    printf("\n*** array after merge %d\n", i );
355    for( n=0; n<ARRAY_LENGTH; n++) printf("array[%d] = %d\n", n , dst_array[n] );
356#endif
357
358#if CHECK_RESULT
359    int    success = 1;
360    int *  res_array = ( (threads ==   2) ||
361                         (threads ==   8) || 
362                         (threads ==  32) || 
363                         (threads == 128) || 
364                         (threads == 512) ) ? array1 : array0;
365
366    for( n=0 ; n<(ARRAY_LENGTH-2) ; n++ )
367    {
368        if ( res_array[n] > res_array[n+1] )
369        {
370            printf("\n[sort] array[%d] = %d > array[%d] = %d\n",
371            n , res_array[n] , n+1 , res_array[n+1] );
372            success = 0;
373            break;
374        }
375    }
376
377    if ( success ) printf("\n[sort] success\n");
378    else           printf("\n[sort] failure\n");
379#endif
380
381#if INSTRUMENTATION
382    char               name[64];
383    char               path[128];
384    unsigned long long instru_cycle;
385
386    // build file name
387    if( USE_DQT_BARRIER )
388    snprintf( name , 64 , "p_sort_dqt_%d_%d_%d", ARRAY_LENGTH, x_size * y_size, ncores );
389    else
390    snprintf( name , 64 , "p_sort_smp_%d_%d_%d", ARRAY_LENGTH, x_size * y_size, ncores );
391
392    // build file pathname
393    snprintf( path , 128 , "home/%s" , name );
394
395    // compute results
396    unsigned int sequencial = (unsigned int)(seq_end_cycle - start_cycle);
397    unsigned int parallel   = (unsigned int)(para_end_cycle - seq_end_cycle);
398
399    // display results on process terminal
400    printf("\n----- %s -----\n"
401           " - sequencial : %d cycles\n"
402           " - parallel   : %d cycles\n", 
403           name, sequencial, parallel );
404
405    // open file
406    get_cycle( &instru_cycle );
407    FILE * stream = fopen( path , NULL );
408
409    if( stream == NULL )
410    {
411        printf("\n[sort] ERROR : cannot open instrumentation file <%s>\n", path );
412        exit(0);
413    }
414
415    printf("\n[sort] file <%s> open at cycle %d\n", path, (unsigned int)instru_cycle );
416
417#if IDBG
418idbg();
419#endif
420
421    // register results to file
422    get_cycle( &instru_cycle );
423    int ret = fprintf( stream , "\n----- %s -----\n"
424                                " - sequencial : %d cycles\n"
425                                " - parallel   : %d cycles\n", name, sequencial, parallel );
426    if( ret < 0 )
427    {
428        printf("\n[sort] ERROR : cannot write to instrumentation file <%s>\n", path );
429        exit(0);
430    }
431
432    printf("\n[sort] file <%s> written at cycle %d\n", path, (unsigned int)instru_cycle );
433
434#if IDBG
435idbg();
436#endif
437
438    // close instrumentation file
439    get_cycle( &instru_cycle );
440    ret = fclose( stream );
441
442    if( ret )
443    {
444        printf("\n[sort] ERROR : cannot close instrumentation file <%s>\n", path );
445        exit(0);
446    }
447
448    printf("\n[sort] file <%s> closed at cycle %d\n", path, (unsigned int)instru_cycle );
449
450#endif
451
452    exit( 0 );
453
454}  // end main()
455
456/*
457vim: tabstop=4 : shiftwidth=4 : expandtab
458*/
Note: See TracBrowser for help on using the repository browser.