File: thread_queue.cpp

package info (click to toggle)
magma-rocm 2.9.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 83,540 kB
  • sloc: cpp: 709,115; fortran: 121,916; ansic: 32,343; python: 25,603; f90: 15,208; makefile: 945; xml: 253; csh: 232; sh: 203; perl: 104
file content (290 lines) | stat: -rw-r--r-- 9,652 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
83
84
85
86
87
88
89
90
91
92
93
94
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
    -- MAGMA (version 2.9.0) --
       Univ. of Tennessee, Knoxville
       Univ. of California, Berkeley
       Univ. of Colorado, Denver
       @date January 2025

       @author Mark Gates
*/

#include "thread_queue.hpp"

// If err, prints error and throws exception.
static void check( int err )
{
    if ( err != 0 ) {
        fprintf( stderr, "Error: %s (%d)\n", strerror(err), err );
        throw std::exception();
    }
}


/***************************************************************************//**
    @class magma_thread_queue
    
    TODO: replace with OpenMP tasks.
    
    Purpose
    -------
    Implements a thread pool with a multi-producer, multi-consumer queue.
    
    Typical use:
    A main thread creates the queue and tells it to launch worker threads. Then
    the main thread inserts (pushes) tasks into the queue. Threads will execute
    the tasks. No dependencies are tracked. The main thread can sync the queue,
    waiting for all current tasks to finish, and then insert more tasks into the
    queue. When finished, the main thread calls quit or simply destructs the
    queue, which will exit all worker threads.
    
    Tasks are sub-classes of magma_task. They must implement the run() function.
    
    Example
    -------
    @code
    class task1: public magma_task {
    public:
        task1( int arg ):
            m_arg( arg ) {}
        
        virtual void run() { do_task1( m_arg ); }
    private:
        int m_arg;
    };
    
    class task2: public magma_task {
    public:
        task2( int arg1, int arg2 ):
            m_arg1( arg1 ), m_arg2( arg2 ) {}
        
        virtual void run() { do_task2( m_arg1, m_arg2 ); }
    private:
        int m_arg1, m_arg2;
    };
    
    void master( int n ) {
        magma_thread_queue queue;
        queue.launch( 12 );  // 12 worker threads
        for( int i=0; i < n; ++i ) {
            queue.push_task( new task1( i ));
        }
        queue.sync();  // wait for all task1 to finish before doing task2.
        for( int i=0; i < n; ++i ) {
            for( int j=0; j < i; ++j ) {
                queue.push_task( new task2( i, j ));
            }
        }
        queue.quit();  // [optional] explicitly exit worker threads
    }
    @endcode
    
    This is similar to python's queue class, but also implements worker threads
    and adds quit() mechanism. sync() is like python's join, but threads do not
    exit, so join would be a misleading name.
    
    @ingroup magma_thread
*******************************************************************************/


/***************************************************************************//**
    Thread's main routine, executed by pthread_create.
    Executes tasks from queue (given as arg), until a NULL task is returned.
    Deletes each task when it is done.
    @param[in,out] arg    magma_thread_queue to get tasks from.
*******************************************************************************/
extern "C"
void* magma_thread_main( void* arg )
{
    magma_thread_queue* queue = (magma_thread_queue*) arg;
    magma_task* task;
    
    while( true ) {
        task = queue->pop_task();
        if ( task == NULL ) {
            break;
        }
        
        task->run();
        queue->task_done();
        delete task;
        task = NULL;
    }
    
    return NULL;  // implicitly does pthread_exit
}


/***************************************************************************//**
    Creates queue with NO threads. Use launch() to create threads.
*******************************************************************************/
magma_thread_queue::magma_thread_queue():
    q        (),
    quit_flag( false ),
    ntask    ( 0     ),
    threads  ( NULL  ),
    nthread  ( 0     )
{
    check( pthread_mutex_init( &mutex,      NULL ));
    check( pthread_cond_init(  &cond,       NULL ));
    check( pthread_cond_init(  &cond_ntask, NULL ));
}


/***************************************************************************//**
    Calls quit(), then deallocates data.
*******************************************************************************/
magma_thread_queue::~magma_thread_queue()
{
    quit();
    check( pthread_mutex_destroy( &mutex ));
    check( pthread_cond_destroy( &cond ));
    check( pthread_cond_destroy( &cond_ntask ));
}


/***************************************************************************//**
    Creates threads.
    @param[in] in_nthread    Number of threads to launch.
*******************************************************************************/
void magma_thread_queue::launch( magma_int_t in_nthread )
{
    assert( threads == NULL );  // else launch was called previously
    nthread = in_nthread;
    if ( nthread < 1 ) {
        nthread = 1;
    }
    threads = new pthread_t[ nthread ];
    for( magma_int_t i=0; i < nthread; ++i ) {
        check( pthread_create( &threads[i], NULL, magma_thread_main, this ));
        //printf( "launch %d (%lx)\n", i, (long) threads[i] );
    }
}


/***************************************************************************//**
    Add task to queue. Task must be allocated with C++ new.
    Increments number of outstanding tasks.
    Signals threads that are waiting in pop_task().
    @param[in] task    Task to queue.
*******************************************************************************/
void magma_thread_queue::push_task( magma_task* task )
{
    check( pthread_mutex_lock( &mutex ));
    if ( quit_flag ) {
        fprintf( stderr, "Error: push_task() called after quit()\n" );
        throw std::exception();
    }
    q.push( task );
    ntask += 1;
    //printf( "push; ntask %d\n", ntask );
    check( pthread_cond_broadcast( &cond ));
    check( pthread_mutex_unlock( &mutex ));
}


/***************************************************************************//**
    Get next task from queue.
    @return next task, blocking until a task is inserted if necesary.
    @return NULL if queue is empty *and* quit() has been called.
    
    This does *not* decrement number of outstanding tasks;
    thread should call task_done() when task is completed.
*******************************************************************************/
magma_task* magma_thread_queue::pop_task()
{
    magma_task* task = NULL;
    check( pthread_mutex_lock( &mutex ));
    while( q.empty() && ! quit_flag ) {
        check( pthread_cond_wait( &cond, &mutex ));
    }
    // q has item or quit is set (or both)
    if ( ! q.empty()) {
        task = q.front();
        q.pop();
    }
    //printf( "pop;  ntask %d\n", ntask );
    check( pthread_mutex_unlock( &mutex ));
    return task;
}


/***************************************************************************//**
    Marks task as finished, decrementing number of outstanding tasks.
    Signals threads that are waiting in sync().
*******************************************************************************/
void magma_thread_queue::task_done()
{
    check( pthread_mutex_lock( &mutex ));
    ntask -= 1;
    //printf( "fini; ntask %d\n", ntask );
    check( pthread_cond_broadcast( &cond_ntask ));
    check( pthread_mutex_unlock( &mutex ));
}


/***************************************************************************//**
    Block until all outstanding tasks have been finished.
    Threads continue to be alive; more tasks can be pushed after sync.
*******************************************************************************/
void magma_thread_queue::sync()
{
    check( pthread_mutex_lock( &mutex ));
    //printf( "sync; ntask %d [start]\n", ntask );
    while( ntask > 0 ) {
        check( pthread_cond_wait( &cond_ntask, &mutex ));
        //printf( "sync; ntask %d\n", ntask );
    }
    //printf( "sync; ntask %d [done]\n", ntask );
    check( pthread_mutex_unlock( &mutex ));
}


/***************************************************************************//**
    Sets quit_flag, so pop_task() will return NULL once queue is empty,
    telling threads to exit.
    Signals all threads that are waiting in pop_task().
    Waits for all threads to exit (i.e., joins them).
    It is safe to call quit multiple times -- the first time all the threads are
    joined; subsequent times it does nothing.
    (Destructor also calls quit, but you may prefer to call it explicitly.)
*******************************************************************************/
void magma_thread_queue::quit()
{
    // first, set quit_flag and signal waiting threads
    bool join = true;
    check( pthread_mutex_lock( &mutex ));
    //printf( "quit %d\n", quit_flag );
    if ( quit_flag ) {
        join = false;  // quit previously called; don't join again.
    }
    else {
        quit_flag = true;
        check( pthread_cond_broadcast( &cond ));
    }
    check( pthread_mutex_unlock( &mutex ));
    
    // next, join all threads
    if ( join ) {
        assert( threads != NULL );
        for( magma_int_t i=0; i < nthread; ++i ) {
            check( pthread_join( threads[i], NULL ));
            //printf( "joined %d (%lx)\n", i, (long) threads[i] );
        }
        delete[] threads;
        threads = NULL;
    }
}


/***************************************************************************//**
    Mostly for debugging, returns thread index in range 0, ..., nthread-1.
*******************************************************************************/
magma_int_t magma_thread_queue::get_thread_index( pthread_t thread ) const
{
    for( magma_int_t i=0; i < nthread; ++i ) {
        if ( pthread_equal( thread, threads[i] )) {
            return i;
        }
    }
    return -1;
}