Welcome to mirror list, hosted at ThFree Co, Russian Federation.

threaded_queue.cc « cygwin « winsup - cygwin.com/git/newlib-cygwin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ba0fe417843f68b385586c9dd3a4407e69f5ef16 (plain)
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/* threaded_queue.cc

   Copyright 2001, 2002 Red Hat Inc.

   Written by Robert Collins <rbtcollins@hotmail.com>

This file is part of Cygwin.

This software is a copyrighted work licensed under the terms of the
Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
details. */

#include "woutsup.h"

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include "threaded_queue.h"

/*****************************************************************************/

/* queue_request */

queue_request::~queue_request ()
{}

/*****************************************************************************/

/* threaded_queue */

threaded_queue::threaded_queue (const size_t initial_workers)
  : _workers_count (0),
    _running (false),
    _submitters_head (NULL),
    _requests_count (0),
    _requests_head (NULL),
    _requests_sem (NULL)
{
  InitializeCriticalSection (&_queue_lock);

  // This semaphore's count is the number of requests on the queue.
  // The maximum count (129792) is calculated as MAXIMUM_WAIT_OBJECTS
  // multiplied by max. threads per process (2028?), which is (a few)
  // more requests than could ever be pending with the current design.

  _requests_sem = CreateSemaphore (NULL,   // SECURITY_ATTRIBUTES
				   0,	   // Initial count
				   129792, // Maximum count
				   NULL);  // Anonymous

  if (!_requests_sem)
    {
      system_printf (("failed to create the request queue semaphore, "
		      "error = %lu"),
		     GetLastError ());
      abort ();
    }

  create_workers (initial_workers);
}

threaded_queue::~threaded_queue ()
{
  if (_running)
    stop ();

  debug_printf ("deleting all pending queue requests");
  queue_request *reqptr = _requests_head;
  while (reqptr)
    {
      queue_request *const ptr = reqptr;
      reqptr = reqptr->_next;
      safe_delete (ptr);
    }

  DeleteCriticalSection (&_queue_lock);
  if (_requests_sem)
    (void) CloseHandle (_requests_sem);
}

/* FIXME: return success or failure rather than quitting */
void
threaded_queue::add_submission_loop (queue_submission_loop *const submitter)
{
  assert (this);
  assert (submitter);
  assert (submitter->_queue == this);
  assert (!submitter->_next);

  submitter->_next =
    TInterlockedExchangePointer (&_submitters_head, submitter);

  if (_running)
    submitter->start ();
}

bool
threaded_queue::start ()
{
  EnterCriticalSection (&_queue_lock);
  const bool was_running = _running;
  _running = true;
  queue_submission_loop *loopptr = _submitters_head;
  LeaveCriticalSection (&_queue_lock);

  if (!was_running)
    {
      debug_printf ("starting all queue submission loops");

      while (loopptr)
	{
	  queue_submission_loop *const ptr = loopptr;
	  loopptr = loopptr->_next;
	  ptr->start ();
	}
    }

  return was_running;
}

bool
threaded_queue::stop ()
{
  EnterCriticalSection (&_queue_lock);
  const bool was_running = _running;
  _running = false;
  queue_submission_loop *loopptr = _submitters_head;
  LeaveCriticalSection (&_queue_lock);

  if (was_running)
    {
      debug_printf ("stopping all queue submission loops");
      while (loopptr)
	{
	  queue_submission_loop *const ptr = loopptr;
	  loopptr = loopptr->_next;
	  ptr->stop ();
	}

      ReleaseSemaphore (_requests_sem, _workers_count, NULL);
      while (_workers_count)
	{
	  debug_printf (("waiting for worker threads to terminate: "
			 "%lu still running"),
			_workers_count);
	  Sleep (1000);
	}
      debug_printf ("all worker threads have terminated");
    }

  return was_running;
}

/* FIXME: return success or failure */
void
threaded_queue::add (queue_request *const therequest)
{
  assert (this);
  assert (therequest);
  assert (!therequest->_next);

  if (!_workers_count)
    {
      system_printf ("warning: no worker threads to handle request!");
      // FIXME: And then what?
    }

  EnterCriticalSection (&_queue_lock);
  if (!_requests_head)
    _requests_head = therequest;
  else
    {
      /* Add to the queue end. */
      queue_request *reqptr = _requests_head;
      for (; reqptr->_next; reqptr = reqptr->_next)
	{}
      assert (reqptr);
      assert (!reqptr->_next);
      reqptr->_next = therequest;
    }

  _requests_count += 1;
  assert (_requests_count > 0);
  LeaveCriticalSection (&_queue_lock);

  (void) ReleaseSemaphore (_requests_sem, 1, NULL);
}

/*static*/ DWORD WINAPI
threaded_queue::start_routine (const LPVOID lpParam)
{
  class threaded_queue *const queue = (class threaded_queue *) lpParam;
  assert (queue);

  queue->worker_loop ();

  const long count = InterlockedDecrement (&queue->_workers_count);
  assert (count >= 0);

  if (queue->_running)
    debug_printf ("worker loop has exited; thread about to terminate");

  return 0;
}

/* Called from the constructor: so no need to be thread-safe until the
 * worker threads start to be created; thus the interlocked increment
 * of the `_workers_count' field.
 */

void
threaded_queue::create_workers (const size_t initial_workers)
{
  assert (initial_workers > 0);

  for (unsigned int i = 0; i != initial_workers; i++)
    {
      const long count = InterlockedIncrement (&_workers_count);
      assert (count > 0);

      DWORD tid;
      const HANDLE hThread =
	CreateThread (NULL, 0, start_routine, this, 0, &tid);

      if (!hThread)
	{
	  system_printf ("failed to create thread, error = %lu",
			 GetLastError ());
	  abort ();
	}

      (void) CloseHandle (hThread);
    }
}

void
threaded_queue::worker_loop ()
{
  while (true)
    {
      const DWORD rc = WaitForSingleObject (_requests_sem, INFINITE);
      if (rc == WAIT_FAILED)
	{
	  system_printf ("wait for request semaphore failed, error = %lu",
			 GetLastError ());
	  return;
	}
      assert (rc == WAIT_OBJECT_0);

      EnterCriticalSection (&_queue_lock);
      if (!_running)
	{
	  LeaveCriticalSection (&_queue_lock);
	  return;
	}

      assert (_requests_head);
      queue_request *const reqptr = _requests_head;
      _requests_head = reqptr->_next;

      _requests_count -= 1;
      assert (_requests_count >= 0);
      LeaveCriticalSection (&_queue_lock);

      assert (reqptr);
      reqptr->process ();
      safe_delete (reqptr);
    }
}

/*****************************************************************************/

/* queue_submission_loop */

queue_submission_loop::queue_submission_loop (threaded_queue *const queue,
					      const bool ninterruptible)
  : _running (false),
    _interrupt_event (NULL),
    _queue (queue),
    _interruptible (ninterruptible),
    _hThread (NULL),
    _tid (0),
    _next (NULL)
{
  if (_interruptible)
    {
      // verbose: debug_printf ("creating an interruptible processing thread");

      _interrupt_event = CreateEvent (NULL,  // SECURITY_ATTRIBUTES
				      FALSE, // Auto-reset
				      FALSE, // Initially non-signalled
				      NULL); // Anonymous

      if (!_interrupt_event)
	{
	  system_printf ("failed to create interrupt event, error = %lu",
			 GetLastError ());
	  abort ();
	}
    }
}

queue_submission_loop::~queue_submission_loop ()
{
  if (_running)
    stop ();
  if (_interrupt_event)
    (void) CloseHandle (_interrupt_event);
  if (_hThread)
    (void) CloseHandle (_hThread);
}

bool
queue_submission_loop::start ()
{
  assert (this);
  assert (!_hThread);

  const bool was_running = _running;

  if (!was_running)
    {
      _running = true;

      _hThread = CreateThread (NULL, 0, start_routine, this, 0, &_tid);
      if (!_hThread)
	{
	  system_printf ("failed to create thread, error = %lu",
			 GetLastError ());
	  abort ();
	}
    }

  return was_running;
}

bool
queue_submission_loop::stop ()
{
  assert (this);
  assert (_hThread && _hThread != INVALID_HANDLE_VALUE);

  const bool was_running = _running;

  if (_running)
    {
      _running = false;

      if (_interruptible)
	{
	  assert (_interrupt_event
		  && _interrupt_event != INVALID_HANDLE_VALUE);

	  SetEvent (_interrupt_event);

	  if (WaitForSingleObject (_hThread, 1000) == WAIT_TIMEOUT)
	    {
	      system_printf (("request loop thread %lu failed to shutdown "
			      "when asked politely: about to get heavy"),
			     _tid);

	      if (!TerminateThread (_hThread, 0))
		{
		  system_printf (("failed to kill request loop thread %lu"
				  ", error = %lu"),
				 _tid, GetLastError ());
		  abort ();
		}
	    }
	}
      else
	{
	  // FIXME: could wait to see if the request loop notices that
	  // the submission loop is no longer running and shuts down
	  // voluntarily.

	  debug_printf ("killing request loop thread %lu", _tid);

	  if (!TerminateThread (_hThread, 0))
	    system_printf (("failed to kill request loop thread %lu"
			    ", error = %lu"),
			   _tid, GetLastError ());
	}
    }

  return was_running;
}

/*static*/ DWORD WINAPI
queue_submission_loop::start_routine (const LPVOID lpParam)
{
  class queue_submission_loop *const submission_loop =
    (class queue_submission_loop *) lpParam;
  assert (submission_loop);

  submission_loop->request_loop ();

  debug_printf ("submission loop has exited; thread about to terminate");

  submission_loop->stop ();

  return 0;
}

/*****************************************************************************/