summaryrefslogtreecommitdiff
path: root/ace/Token.cpp
blob: cb2b2d2c618a8bda527ae71590a45c82f95daebc (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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// $Id$

#include "ace/Thread.h"
#include "ace/Token.h"
#include "ace/Log_Msg.h"

#if defined (DEBUGGING)
#include "ace/streams.h"
#endif /* DEBUGGING */

ACE_RCSID(ace, Token, "$Id$")

#if defined (ACE_HAS_THREADS)

#if !defined (__ACE_INLINE__)
#include "ace/Synch_T.h"
#include "ace/Token.i"
#endif /* __ACE_INLINE__ */

ACE_ALLOC_HOOK_DEFINE(ACE_Token)


void
ACE_Token::dump (void) const
{
  ACE_TRACE ("ACE_Token::dump");

  ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));

  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\nthread = %d"), ACE_Thread::self ()));
  // @@ Is there a portable way to do this?
  // ACE_DEBUG ((LM_DEBUG, "\nowner_ = %l", (long) this->owner_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\nowner_ addr = %x"), &this->owner_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\nwaiters_ = %d"), this->waiters_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\nin_use_ = %d"), this->in_use_));
  ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("\nnesting level = %d"), this->nesting_level_));
  ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
}

ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry (ACE_Thread_Mutex &m,
                                                         ACE_thread_t t_id)
  : next_ (0),
    thread_id_ (t_id),
#if defined (ACE_TOKEN_USES_SEMAPHORE)
    cv_ (0),
#else
    cv_ (m),
#endif /* ACE_TOKEN_USES_SEMAPHORE */
    runable_ (0)
{
#if defined (ACE_TOKEN_USES_SEMAPHORE)
  ACE_UNUSED_ARG (m);
#endif /* ACE_TOKEN_USES_SEMAPHORE */

  ACE_TRACE ("ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry");
}

ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry (ACE_Thread_Mutex &m,
                                                         ACE_thread_t t_id,
                                                         ACE_Condition_Attributes &attributes)
  : next_ (0),
    thread_id_ (t_id),
#if defined (ACE_TOKEN_USES_SEMAPHORE)
    cv_ (0),
#else
    cv_ (m, attributes),
#endif /* ACE_TOKEN_USES_SEMAPHORE */
    runable_ (0)
{
#if defined (ACE_TOKEN_USES_SEMAPHORE)
  ACE_UNUSED_ARG (m);
  ACE_UNUSED_ARG (attributes);
#endif /* ACE_TOKEN_USES_SEMAPHORE */

  ACE_TRACE ("ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry");
}

ACE_Token::ACE_Token_Queue::ACE_Token_Queue (void)
  : head_ (0),
    tail_ (0)
{
  ACE_TRACE ("ACE_Token::ACE_Token_Queue::ACE_Token_Queue");
}

//
// Remove an entry from the list.  Must be called with locks held.
//
void
ACE_Token::ACE_Token_Queue::remove_entry (ACE_Token::ACE_Token_Queue_Entry *entry)
{
  ACE_TRACE ("ACE_Token::ACE_Token_Queue::remove_entry");
  ACE_Token_Queue_Entry *curr = 0;
  ACE_Token_Queue_Entry *prev = 0;

  if (this->head_ == 0)
    return;

  for (curr = this->head_;
       curr != 0 && curr != entry;
       curr = curr->next_)
    prev = curr;

  if (curr == 0)
    // Didn't find the entry...
    return;
  else if (prev == 0)
    // Delete at the head.
    this->head_ = this->head_->next_;
  else
    // Delete in the middle.
    prev->next_ = curr->next_;

  // We need to update the tail of the list if we've deleted the last
  // entry.
  if (curr->next_ == 0)
    this->tail_ = prev;
}

//
// Add an entry into the list.  Must be called with locks held.
//
void
ACE_Token::ACE_Token_Queue::insert_entry (ACE_Token::ACE_Token_Queue_Entry &entry,
                                          int requeue_position)
{
  if (this->head_ == 0)
    {
      // No other threads - just add me
      this->head_ = &entry;
      this->tail_ = &entry;
    }
  else if (requeue_position == -1)
    {
      // Insert at the end of the queue.
      this->tail_->next_ = &entry;
      this->tail_ = &entry;
    }
  else if (requeue_position == 0)
    {
      // Insert at head of queue.
      entry.next_ = this->head_;
      this->head_ = &entry;
    }
  else
    // Insert in the middle of the queue somewhere.
    {
      // Determine where our thread should go in the queue of waiters.

      ACE_Token::ACE_Token_Queue_Entry *insert_after = this->head_;
      while (requeue_position-- && insert_after->next_ != 0)
        insert_after = insert_after->next_;

      entry.next_ = insert_after->next_;

      if (entry.next_ == 0)
        this->tail_ = &entry;

      insert_after->next_ = &entry;
    }
}

ACE_Token::ACE_Token (const ACE_TCHAR *name, void *any)
  : lock_ (name, (ACE_mutexattr_t *) any),
    owner_ (ACE_OS::NULL_thread),
    in_use_ (0),
    waiters_ (0),
    nesting_level_ (0),
    attributes_ (USYNC_THREAD)
{
//  ACE_TRACE ("ACE_Token::ACE_Token");
}

ACE_Token::~ACE_Token (void)
{
  ACE_TRACE ("ACE_Token::~ACE_Token");
}

int
ACE_Token::shared_acquire (void (*sleep_hook_func)(void *),
                           void *arg,
                           ACE_Time_Value *timeout,
                           ACE_Token_Op_Type op_type)
{
  ACE_TRACE ("ACE_Token::shared_acquire");
  ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1);

#if defined (DEBUGGING)
  this->dump ();
#endif /* DEBUGGING */

  ACE_thread_t thr_id = ACE_Thread::self ();

  // Nobody holds the token.
  if (!this->in_use_)
    {
      // Its mine!
      this->in_use_ = op_type;
      this->owner_ = thr_id;
      return 0;
    }

  //
  // Someone already holds the token.
  //

  // Check if it is us.
  if (ACE_OS::thr_equal (thr_id, this->owner_))
    {
      this->nesting_level_++;
      return 0;
    }

  // Do a quick check for "polling" behavior.
  if (timeout != 0 && timeout->sec () == 0 && timeout->usec () == 0)
    {
      errno = ETIME;
      return -1;
    }

  //
  // We've got to sleep until we get the token.
  //

  // Which queue we should end up in...
  ACE_Token_Queue *queue = (op_type == ACE_Token::READ_TOKEN
                            ? &this->readers_
                            : &this->writers_);

  // Allocate queue entry on stack.  This works since we don't exit
  // this method's activation record until we've got the token.
  ACE_Token::ACE_Token_Queue_Entry my_entry (this->lock_,
                                             thr_id,
                                             this->attributes_);
  queue->insert_entry (my_entry);
  this->waiters_++;

  // Execute appropriate <sleep_hook> callback.  (@@ should these
  // methods return a success/failure status, and if so, what should
  // we do with it?)
  int ret = 0;
  if (sleep_hook_func)
    {
      (*sleep_hook_func) (arg);
      ret++;
    }
  else
    {
      // Execute virtual method.
      this->sleep_hook ();
      ret++;
    }

  int timed_out = 0;
  int error = 0;

  // Sleep until we've got the token (ignore signals).
  do
    {
      int result = my_entry.wait (timeout,
                                  this->lock_);

      if (result == -1)
        {
          // Note, this should obey whatever thread-specific interrupt
          // policy is currently in place...
          if (errno == EINTR)
            continue;

#if defined (DEBUGGING)
          cerr << '(' << ACE_Thread::self () << ')'
               << " acquire: "
               << (errno == ETIME ? "timed out" : "error occurred")
               << endl;
#endif /* DEBUGGING */

          // We come here if a timeout occurs or some serious
          // ACE_Condition object error.
          if (errno == ETIME)
            timed_out = 1;
          else
            error = 1;

          // Stop the loop.
          break;
        }
    }
  while (!ACE_OS::thr_equal (thr_id, this->owner_));

  // Do this always and irrespective of the result of wait().
  this->waiters_--;
  queue->remove_entry (&my_entry);

#if defined (DEBUGGING)
  cerr << '(' << ACE_Thread::self () << ')'
       << " acquire (UNBLOCKED)" << endl;
#endif /* DEBUGGING */

  // If timeout occured
  if (timed_out)
    {
      // This thread was still selected to own the token.
      if (my_entry.runable_)
        {
          // Wakeup next waiter since this thread timed out.
          this->wakeup_next_waiter ();
        }

      // Return error.
     return -1;
    }
  else if (error)
    {
      // Return error.
      return -1;
    }

  // If this is a normal wakeup, this thread should be runnable.
  ACE_ASSERT (my_entry.runable_);

  return ret;
}

// By default this is a no-op.

/* virtual */
void
ACE_Token::sleep_hook (void)
{
  ACE_TRACE ("ACE_Token::sleep_hook");
}

int
ACE_Token::acquire (ACE_Time_Value *timeout)
{
  ACE_TRACE ("ACE_Token::acquire");
  return this->shared_acquire (0, 0, timeout, ACE_Token::WRITE_TOKEN);
}

// Acquire the token, sleeping until it is obtained or until <timeout>
// expires.

int
ACE_Token::acquire (void (*sleep_hook_func)(void *),
                    void *arg,
                    ACE_Time_Value *timeout)
{
  ACE_TRACE ("ACE_Token::acquire");
  return this->shared_acquire (sleep_hook_func, arg, timeout, ACE_Token::WRITE_TOKEN);
}

// Try to renew the token.

int
ACE_Token::renew (int requeue_position,
                  ACE_Time_Value *timeout)
{
  ACE_TRACE ("ACE_Token::renew");
  ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1);

#if defined (DEBUGGING)
  this->dump ();
#endif /* DEBUGGING */
  // ACE_ASSERT (ACE_OS::thr_equal (ACE_Thread::self (), this->owner_));

  // Check to see if there are any waiters worth giving up the lock
  // for.

  // If no writers and either we are a writer or there are no readers.
  if (this->writers_.head_ == 0 &&
      (this->in_use_ == ACE_Token::WRITE_TOKEN ||
       this->readers_.head_ == 0))
    // Immediate return.
    return 0;

  // We've got to sleep until we get the token again.

  // Determine which queue should this thread go to.
  ACE_Token::ACE_Token_Queue *this_threads_queue =
    this->in_use_ == ACE_Token::READ_TOKEN ?
    &this->readers_ : &this->writers_;

  ACE_Token::ACE_Token_Queue_Entry my_entry (this->lock_,
                                             this->owner_);

  this_threads_queue->insert_entry (my_entry,
                                    requeue_position);
  this->waiters_++;

  // Remember nesting level...
  int save_nesting_level_ = this->nesting_level_;

  // Reset state for new owner.
  this->nesting_level_ = 0;

  // Wakeup waiter.
  this->wakeup_next_waiter ();

  int timed_out = 0;
  int error = 0;

  // Sleep until we've got the token (ignore signals).
  do
    {
      int result = my_entry.wait (timeout,
                                  this->lock_);

      if (result == -1)
        {
          // Note, this should obey whatever thread-specific interrupt
          // policy is currently in place...
          if (errno == EINTR)
            continue;

#if defined (DEBUGGING)
          cerr << '(' << ACE_Thread::self () << ')'
               << " renew: "
               << (errno == ETIME ? "timed out" : "error occurred")
               << endl;
#endif /* DEBUGGING */

          // We come here if a timeout occurs or some serious
          // ACE_Condition object error.
          if (errno == ETIME)
            timed_out = 1;
          else
            error = 1;

          // Stop the loop.
          break;
        }
    }
  while (!ACE_OS::thr_equal (my_entry.thread_id_, this->owner_));

  // Do this always and irrespective of the result of wait().
  this->waiters_--;
  this_threads_queue->remove_entry (&my_entry);

#if defined (DEBUGGING)
  cerr << '(' << ACE_Thread::self () << ')'
       << " acquire (UNBLOCKED)" << endl;
#endif /* DEBUGGING */

  // If timeout occured
  if (timed_out)
    {
      // This thread was still selected to own the token.
      if (my_entry.runable_)
        {
          // Wakeup next waiter since this thread timed out.
          this->wakeup_next_waiter ();
        }

      // Return error.
     return -1;
    }
  else if (error)
    {
      // Return error.
      return -1;
    }

  // If this is a normal wakeup, this thread should be runnable.
  ACE_ASSERT (my_entry.runable_);

  // Reinstate nesting level.
  this->nesting_level_ = save_nesting_level_;

  return 0;
}

// Release the current holder of the token (which had
// better be the caller's thread!).

int
ACE_Token::release (void)
{
  ACE_TRACE ("ACE_Token::release");
  ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1);

  // ACE_ASSERT (ACE_OS::thr_equal (ACE_Thread::self (), this->owner_));

#if defined (DEBUGGING)
  this->dump ();
#endif /* DEBUGGING */

  // Nested release...
  if (this->nesting_level_ > 0)
    --this->nesting_level_;
  else
    {
      //
      // Regular release...
      //

      // Wakeup waiter.
      this->wakeup_next_waiter ();
    }

  return 0;
}

void
ACE_Token::wakeup_next_waiter (void)
{
  ACE_TRACE ("ACE_Token::wakeup_next_waiter");

  // Reset state for new owner.
  this->owner_ = ACE_OS::NULL_thread;
  this->in_use_ = 0;

  // Any waiters...
  if (this->writers_.head_ == 0 &&
      this->readers_.head_ == 0)
    {
      // No more waiters...
      return;
    }

  // Wakeup next waiter.
  ACE_Token_Queue *queue;

  // Writer threads get priority to run first.
  if (this->writers_.head_ != 0)
    {
      this->in_use_ = ACE_Token::WRITE_TOKEN;
      queue = &this->writers_;
    }
  else
    {
      this->in_use_ = ACE_Token::READ_TOKEN;
      queue = &this->readers_;
    }

  // Wake up waiter and make it runable.
  queue->head_->runable_ = 1;
  queue->head_->signal ();

  this->owner_ = queue->head_->thread_id_;
}

#endif /* ACE_HAS_THREADS */

#if defined (ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION)
#elif defined (ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA)
#endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION */