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 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
|
/** Control of executable units within a shared virtual memory space
Copyright (C) 1996-2010 Free Software Foundation, Inc.
Original Author: David Chisnall <csdavec@swan.ac.uk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
<title>NSLock class reference</title>
<ignore> All autogsdoc markup is in the header
*/
#import "common.h"
#define EXPOSE_NSLock_IVARS 1
#define EXPOSE_NSRecursiveLock_IVARS 1
#define EXPOSE_NSCondition_IVARS 1
#define EXPOSE_NSConditionLock_IVARS 1
#define gs_cond_public_t gs_cond_t
#define gs_cond_mutex_public_t gs_cond_mutex_t
#define gs_mutex_public_t gs_mutex_t
#import "GSPrivate.h"
#import "GSPThread.h"
#include <math.h>
#include <stdlib.h>
#import "common.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSException.h"
#import "Foundation/NSThread.h"
#define class_createInstance(C,E) NSAllocateObject(C,E,NSDefaultMallocZone())
static Class baseConditionClass = Nil;
static Class baseConditionLockClass = Nil;
static Class baseLockClass = Nil;
static Class baseRecursiveLockClass = Nil;
static Class tracedConditionClass = Nil;
static Class tracedConditionLockClass = Nil;
static Class tracedLockClass = Nil;
static Class tracedRecursiveLockClass = Nil;
static Class untracedConditionClass = Nil;
static Class untracedConditionLockClass = Nil;
static Class untracedLockClass = Nil;
static Class untracedRecursiveLockClass = Nil;
static BOOL traceLocks = NO;
@implementation NSObject (GSTraceLocks)
+ (BOOL) shouldCreateTraceableLocks: (BOOL)shouldTrace
{
BOOL old = traceLocks;
traceLocks = shouldTrace ? YES : NO;
return old;
}
+ (NSCondition*) tracedCondition
{
return AUTORELEASE([GSTracedCondition new]);
}
+ (NSConditionLock*) tracedConditionLockWithCondition: (NSInteger)value
{
return AUTORELEASE([[GSTracedConditionLock alloc] initWithCondition: value]);
}
+ (NSLock*) tracedLock
{
return AUTORELEASE([GSTracedLock new]);
}
+ (NSRecursiveLock*) tracedRecursiveLock
{
return AUTORELEASE([GSTracedRecursiveLock new]);
}
@end
/* In untraced operations these macros do nothing.
* When tracing they are defined to perform the trace methods of the thread.
*/
#define CHKT(T,X)
#define CHK(X)
/*
* Methods shared between NSLock, NSRecursiveLock, and NSCondition
*
* Note: These methods currently throw exceptions when locks are incorrectly
* acquired. This is compatible with earlier GNUstep behaviour. In OS X 10.5
* and later, these will just NSLog a warning instead. Throwing an exception
* is probably better behaviour, because it encourages developer to fix their
* code.
*/
#define MDEALLOC \
- (void) dealloc\
{\
[self finalize];\
[_name release];\
[super dealloc];\
}
#if defined(HAVE_PTHREAD_MUTEX_OWNER)
#define MDESCRIPTION \
- (NSString*) description\
{\
if (_mutex.__data.__owner)\
{\
if (_name == nil)\
{\
return [NSString stringWithFormat: @"%@ (locked by %llu)",\
[super description], (unsigned long long)_mutex.__data.__owner];\
}\
return [NSString stringWithFormat: @"%@ '%@' (locked by %llu)",\
[super description], _name, (unsigned long long)_mutex.__data.__owner];\
}\
else\
{\
if (_name == nil)\
{\
return [super description];\
}\
return [NSString stringWithFormat: @"%@ '%@'",\
[super description], _name];\
}\
}
#define MISLOCKED \
- (BOOL) isLockedByCurrentThread\
{\
if (GSPrivateThreadID() == (NSUInteger)_mutex.__data.__owner)\
return YES;\
else\
return NO; \
}
#else
#define MDESCRIPTION \
- (NSString*) description\
{\
if (_name == nil)\
{\
return [super description];\
}\
return [NSString stringWithFormat: @"%@ '%@'",\
[super description], _name];\
}
#define MISLOCKED \
- (BOOL) isLockedByCurrentThread\
{\
[NSException raise: NSGenericException format: @"Not supported"];\
return NO;\
}
#endif
#define MFINALIZE \
- (void) finalize\
{\
GS_MUTEX_DESTROY(_mutex);\
}
#define MLOCK \
- (void) lock\
{\
int err = GS_MUTEX_LOCK(_mutex);\
if (EDEADLK == err)\
{\
(*_NSLock_error_handler)(self, _cmd, YES, @"deadlock");\
}\
else if (err != 0)\
{\
[NSException raise: NSLockException format: @"failed to lock mutex"];\
}\
}
#define MLOCKBEFOREDATE \
- (BOOL) lockBeforeDate: (NSDate*)limit\
{\
do\
{\
int err = GS_MUTEX_TRYLOCK(_mutex);\
if (0 == err)\
{\
CHK(Hold) \
return YES;\
}\
GS_YIELD();\
} while ([limit timeIntervalSinceNow] > 0);\
return NO;\
}
#define MNAME \
- (void) setName: (NSString*)newName\
{\
ASSIGNCOPY(_name, newName);\
}\
- (NSString*) name\
{\
return _name;\
}
#define MSTACK \
- (GSStackTrace*) stack \
{ \
return nil; \
}
#define MTRYLOCK \
- (BOOL) tryLock\
{\
int err = GS_MUTEX_TRYLOCK(_mutex);\
if (0 == err) \
{ \
CHK(Hold) \
return YES; \
} \
else \
{ \
return NO;\
} \
}
#define MUNLOCK \
- (void) unlock\
{\
if (0 != GS_MUTEX_UNLOCK(_mutex))\
{\
if (GSPrivateDefaultsFlag(GSMacOSXCompatible))\
{\
NSLog(@"Failed to unlock mutex %@ at %@",\
self, [NSThread callStackSymbols]);\
}\
else \
{\
[NSException raise: NSLockException\
format: @"failed to unlock mutex %@", self];\
}\
}\
CHK(Drop) \
}
static gs_mutex_t deadlock;
#if !GS_USE_WIN32_THREADS_AND_LOCKS
static pthread_mutexattr_t attr_normal;
static pthread_mutexattr_t attr_reporting;
static pthread_mutexattr_t attr_recursive;
#endif
/*
* OS X 10.5 compatibility function to allow debugging deadlock conditions.
*/
void _NSLockError(id obj, SEL _cmd, BOOL stop, NSString *msg)
{
NSLog(@"*** -[%@ %@]: %@ (%@)", [obj class], NSStringFromSelector(_cmd),
msg, obj);
NSLog(@"*** Break on _NSLockError() to debug.");
if (YES == stop)
GS_MUTEX_LOCK(deadlock);
}
NSLock_error_handler *_NSLock_error_handler = _NSLockError;
// Exceptions
NSString *NSLockException = @"NSLockException";
@implementation NSLock
+ (id) allocWithZone: (NSZone*)z
{
if (self == baseLockClass && YES == traceLocks)
{
return class_createInstance(tracedLockClass, 0);
}
return class_createInstance(self, 0);
}
+ (void) initialize
{
static BOOL beenHere = NO;
if (beenHere == NO)
{
beenHere = YES;
#if !GS_USE_WIN32_THREADS_AND_LOCKS
/* Initialise attributes for the different types of mutex.
* We do it once, since attributes can be shared between multiple
* mutexes.
* If we had a pthread_mutexattr_t instance for each mutex, we would
* either have to store it as an ivar of our NSLock (or similar), or
* we would potentially leak instances as we couldn't destroy them
* when destroying the NSLock. I don't know if any implementation
* of pthreads actually allocates memory when you call the
* pthread_mutexattr_init function, but they are allowed to do so
* (and deallocate the memory in pthread_mutexattr_destroy).
*/
pthread_mutexattr_init(&attr_normal);
pthread_mutexattr_settype(&attr_normal, PTHREAD_MUTEX_NORMAL);
pthread_mutexattr_init(&attr_reporting);
pthread_mutexattr_settype(&attr_reporting, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_init(&attr_recursive);
pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE);
#endif
/* To emulate OSX behavior, we need to be able both to detect deadlocks
* (so we can log them), and also hang the thread when one occurs.
* the simple way to do that is to set up a locked mutex we can
* force a deadlock on.
*/
#if GS_USE_WIN32_THREADS_AND_LOCKS
gs_mutex_init(&deadlock, gs_mutex_attr_normal);
#else
pthread_mutex_init(&deadlock, &attr_normal);
#endif
GS_MUTEX_LOCK(deadlock);
baseConditionClass = [NSCondition class];
baseConditionLockClass = [NSConditionLock class];
baseLockClass = [NSLock class];
baseRecursiveLockClass = [NSRecursiveLock class];
tracedConditionClass = [GSTracedCondition class];
tracedConditionLockClass = [GSTracedConditionLock class];
tracedLockClass = [GSTracedLock class];
tracedRecursiveLockClass = [GSTracedRecursiveLock class];
untracedConditionClass = [GSUntracedCondition class];
untracedConditionLockClass = [GSUntracedConditionLock class];
untracedLockClass = [GSUntracedLock class];
untracedRecursiveLockClass = [GSUntracedRecursiveLock class];
}
}
MDEALLOC
MDESCRIPTION
MFINALIZE
/* Use an error-checking lock. This is marginally slower, but lets us throw
* exceptions when incorrect locking occurs.
*/
- (id) init
{
if (nil != (self = [super init]))
{
#if GS_USE_WIN32_THREADS_AND_LOCKS
gs_mutex_init(&_mutex, gs_mutex_attr_errorcheck);
#else
if (0 != pthread_mutex_init(&_mutex, &attr_reporting))
{
DESTROY(self);
}
#endif
}
return self;
}
MISLOCKED
MLOCK
- (BOOL) lockBeforeDate: (NSDate*)limit
{
do
{
int err = GS_MUTEX_TRYLOCK(_mutex);
if (0 == err)
{
CHK(Hold)
return YES;
}
if (EDEADLK == err)
{
(*_NSLock_error_handler)(self, _cmd, NO, @"deadlock");
}
GS_YIELD();
} while ([limit timeIntervalSinceNow] > 0);
return NO;
}
MNAME
MSTACK
MTRYLOCK
MUNLOCK
@end
@implementation NSRecursiveLock
+ (id) allocWithZone: (NSZone*)z
{
if (self == baseRecursiveLockClass && YES == traceLocks)
{
return class_createInstance(tracedRecursiveLockClass, 0);
}
return class_createInstance(self, 0);
}
+ (void) initialize
{
[NSLock class]; // Ensure mutex attributes are set up.
}
MDEALLOC
MDESCRIPTION
MFINALIZE
- (id) init
{
if (nil != (self = [super init]))
{
#if GS_USE_WIN32_THREADS_AND_LOCKS
gs_mutex_init(&_mutex, gs_mutex_attr_recursive);
#else
if (0 != pthread_mutex_init(&_mutex, &attr_recursive))
{
DESTROY(self);
}
#endif
}
return self;
}
MISLOCKED
MLOCK
MLOCKBEFOREDATE
MNAME
MSTACK
MTRYLOCK
MUNLOCK
@end
@implementation NSCondition
+ (id) allocWithZone: (NSZone*)z
{
if (self == baseConditionClass && YES == traceLocks)
{
return class_createInstance(tracedConditionClass, 0);
}
return class_createInstance(self, 0);
}
+ (void) initialize
{
[NSLock class]; // Ensure mutex attributes are set up.
}
- (void) broadcast
{
GS_COND_BROADCAST(_condition);
}
MDEALLOC
MDESCRIPTION
- (void) finalize
{
#if !GS_USE_WIN32_THREADS_AND_LOCKS
pthread_cond_destroy(&_condition);
#endif
GS_MUTEX_DESTROY(_mutex);
}
- (id) init
{
if (nil != (self = [super init]))
{
#if GS_USE_WIN32_THREADS_AND_LOCKS
InitializeConditionVariable(&_condition);
gs_mutex_init(&_mutex, gs_mutex_attr_errorcheck);
#else
if (0 != pthread_cond_init(&_condition, NULL))
{
DESTROY(self);
}
else if (0 != pthread_mutex_init(&_mutex, &attr_reporting))
{
pthread_cond_destroy(&_condition);
DESTROY(self);
}
#endif
}
return self;
}
MISLOCKED
MLOCK
MLOCKBEFOREDATE
MNAME
- (void) signal
{
GS_COND_SIGNAL(_condition);
}
MSTACK
MTRYLOCK
MUNLOCK
- (void) wait
{
GS_COND_WAIT(&_condition, &_mutex);
}
- (BOOL) waitUntilDate: (NSDate*)limit
{
int retVal = 0;
#if GS_USE_WIN32_THREADS_AND_LOCKS
NSTimeInterval ti = [limit timeIntervalSinceNow];
if (ti < 0) {
ti = 0.0; // handle timeout in the past
}
retVal = gs_cond_timedwait(&_condition, &_mutex, ti * 1000.0);
#else
NSTimeInterval ti = [limit timeIntervalSince1970];
double secs, subsecs;
struct timespec timeout;
// Split the float into seconds and fractions of a second
subsecs = modf(ti, &secs);
timeout.tv_sec = secs;
// Convert fractions of a second to nanoseconds
timeout.tv_nsec = subsecs * 1e9;
/* NB. On timeout the lock is still held even through condition is not met
*/
retVal = pthread_cond_timedwait(&_condition, &_mutex, &timeout);
#endif /* GS_USE_WIN32_THREADS_AND_LOCKS */
if (retVal == 0)
{
return YES;
}
if (retVal == ETIMEDOUT)
{
return NO;
}
NSLog(@"Error calling pthread_cond_timedwait: %d", retVal);
return NO;
}
@end
@implementation NSConditionLock
+ (id) allocWithZone: (NSZone*)z
{
if (self == baseConditionLockClass && YES == traceLocks)
{
return class_createInstance(tracedConditionLockClass, 0);
}
return class_createInstance(self, 0);
}
+ (void) initialize
{
[NSLock class]; // Ensure mutex attributes are set up.
}
- (NSInteger) condition
{
return _condition_value;
}
- (void) dealloc
{
[_name release];
[_condition release];
[super dealloc];
}
- (id) init
{
return [self initWithCondition: 0];
}
- (id) initWithCondition: (NSInteger)value
{
if (nil != (self = [super init]))
{
if (nil == (_condition = [NSCondition new]))
{
DESTROY(self);
}
else
{
_condition_value = value;
[_condition setName:
[NSString stringWithFormat: @"condition-for-lock-%p", self]];
}
}
return self;
}
- (BOOL) isLockedByCurrentThread
{
return [_condition isLockedByCurrentThread];
}
- (void) lock
{
[_condition lock];
}
- (BOOL) lockBeforeDate: (NSDate*)limit
{
return [_condition lockBeforeDate: limit];
}
- (void) lockWhenCondition: (NSInteger)value
{
[_condition lock];
while (value != _condition_value)
{
[_condition wait];
}
}
- (BOOL) lockWhenCondition: (NSInteger)condition_to_meet
beforeDate: (NSDate*)limitDate
{
if (NO == [_condition lockBeforeDate: limitDate])
{
return NO; // Not locked
}
if (condition_to_meet == _condition_value)
{
return YES; // Keeping the lock
}
while ([_condition waitUntilDate: limitDate])
{
if (condition_to_meet == _condition_value)
{
return YES; // Keeping the lock
}
}
[_condition unlock];
return NO; // Not locked
}
MNAME
MSTACK
- (BOOL) tryLock
{
return [_condition tryLock];
}
- (BOOL) tryLockWhenCondition: (NSInteger)condition_to_meet
{
if ([_condition tryLock])
{
if (condition_to_meet == _condition_value)
{
return YES; // KEEP THE LOCK
}
else
{
[_condition unlock];
}
}
return NO;
}
- (void) unlock
{
[_condition unlock];
}
- (void) unlockWithCondition: (NSInteger)value
{
_condition_value = value;
[_condition broadcast];
[_condition unlock];
}
@end
/* Versions of the lock classes where the locking is unconditionally traced
*/
#undef CHKT
#define CHKT(T,X) \
{ \
NSString *msg = [T mutex ## X: self]; \
if (nil != msg) \
{ \
(*_NSLock_error_handler)(self, _cmd, YES, msg); \
} \
}
#undef CHK
#define CHK(X) CHKT(GSCurrentThread(), X)
#undef MDEALLOC
#define MDEALLOC \
- (void) dealloc \
{ \
DESTROY(stack); \
[super dealloc]; \
}
#undef MLOCK
#define MLOCK \
- (void) lock\
{ \
NSThread *t = GSCurrentThread(); \
int err; \
CHKT(t,Wait) \
err = GS_MUTEX_LOCK(_mutex);\
if (EDEADLK == err)\
{\
CHKT(t,Drop) \
(*_NSLock_error_handler)(self, _cmd, YES, @"deadlock");\
}\
else if (err != 0)\
{\
CHKT(t,Drop) \
[NSException raise: NSLockException format: @"failed to lock mutex"];\
}\
CHKT(t,Hold) \
}
#undef MSTACK
#define MSTACK \
- (GSStackTrace*) stack \
{ \
if (nil == stack) \
{ \
stack = [GSStackTrace new]; \
} \
return stack; \
}
@implementation GSTracedCondition
+ (id) allocWithZone: (NSZone*)z
{
return class_createInstance(tracedConditionClass, 0);
}
MDEALLOC
MLOCK
MLOCKBEFOREDATE
MSTACK
MTRYLOCK
- (void) wait
{
NSThread *t = GSCurrentThread();
CHKT(t,Drop)
CHKT(t,Wait)
GS_COND_WAIT(&_condition, &_mutex);
CHKT(t,Hold)
}
- (BOOL) waitUntilDate: (NSDate*)limit
{
int retVal = 0;
NSThread *t = GSCurrentThread();
#if GS_USE_WIN32_THREADS_AND_LOCKS
NSTimeInterval ti = [limit timeIntervalSinceNow];
if (ti < 0) {
ti = 0.0; // handle timeout in the past
}
CHKT(t,Drop)
retVal = gs_cond_timedwait(&_condition, &_mutex, ti * 1000.0);
#else
NSTimeInterval ti = [limit timeIntervalSince1970];
double secs, subsecs;
struct timespec timeout;
// Split the float into seconds and fractions of a second
subsecs = modf(ti, &secs);
timeout.tv_sec = secs;
// Convert fractions of a second to nanoseconds
timeout.tv_nsec = subsecs * 1e9;
/* NB. On timeout the lock is still held even through condition is not met
*/
CHKT(t,Drop)
retVal = pthread_cond_timedwait(&_condition, &_mutex, &timeout);
#endif /* GS_USE_WIN32_THREADS_AND_LOCKS */
if (retVal == 0)
{
CHKT(t,Hold)
return YES;
}
if (retVal == ETIMEDOUT)
{
CHKT(t,Hold)
return NO;
}
NSLog(@"Error calling pthread_cond_timedwait: %d", retVal);
return NO;
}
MUNLOCK
@end
@implementation GSTracedConditionLock
+ (id) allocWithZone: (NSZone*)z
{
return class_createInstance(tracedConditionLockClass, 0);
}
- (id) initWithCondition: (NSInteger)value
{
if (nil != (self = [super init]))
{
if (nil == (_condition = [GSTracedCondition new]))
{
DESTROY(self);
}
else
{
_condition_value = value;
[_condition setName:
[NSString stringWithFormat: @"condition-for-lock-%p", self]];
}
}
return self;
}
@end
@implementation GSTracedLock
+ (id) allocWithZone: (NSZone*)z
{
return class_createInstance(tracedLockClass, 0);
}
MDEALLOC
MLOCK
MLOCKBEFOREDATE
MSTACK
MTRYLOCK
MUNLOCK
@end
@implementation GSTracedRecursiveLock
+ (id) allocWithZone: (NSZone*)z
{
return class_createInstance(tracedRecursiveLockClass, 0);
}
MDEALLOC
MLOCK
MLOCKBEFOREDATE
MSTACK
MTRYLOCK
MUNLOCK
@end
/* Versions of the lock classes where the locking is never traced
*/
@implementation GSUntracedCondition
+ (id) allocWithZone: (NSZone*)z
{
return class_createInstance(baseConditionClass, 0);
}
@end
@implementation GSUntracedConditionLock
+ (id) allocWithZone: (NSZone*)z
{
return class_createInstance(baseConditionLockClass, 0);
}
@end
@implementation GSUntracedLock
+ (id) allocWithZone: (NSZone*)z
{
return class_createInstance(baseRecursiveLockClass, 0);
}
@end
@implementation GSUntracedRecursiveLock
+ (id) allocWithZone: (NSZone*)z
{
return class_createInstance(baseRecursiveLockClass, 0);
}
@end
/* Return a global recursive lock
*/
NSRecursiveLock *
GSPrivateGlobalLock()
{
static NSRecursiveLock *lock = nil;
if (nil == lock)
{
static gs_mutex_t lockLock = GS_MUTEX_INIT_STATIC;
GS_MUTEX_LOCK(lockLock);
if (nil == lock)
{
lock = [GSUntracedRecursiveLock new];
}
GS_MUTEX_UNLOCK(lockLock);
}
return lock;
}
/*
* Pthread-like locking primitives using Windows SRWLock. Provides
* normal, recursive, and error-checked locks.
*/
#if GS_USE_WIN32_THREADS_AND_LOCKS
void
gs_mutex_init(gs_mutex_t *mutex, gs_mutex_attr_t attr)
{
memset(mutex, 0, sizeof(gs_mutex_t));
InitializeSRWLock(&mutex->lock);
mutex->attr = attr;
}
int
gs_mutex_lock(gs_mutex_t *mutex)
{
DWORD thisThread = GetCurrentThreadId();
DWORD ownerThread;
// fast path if lock is not taken
if (TryAcquireSRWLockExclusive(&mutex->lock))
{
assert(mutex->depth == 0);
mutex->depth = 1;
gs_atomic_store(&mutex->owner, thisThread);
return 0;
}
// needs to be atomic because another thread can concurrently set it
ownerThread = gs_atomic_load(&mutex->owner);
if (ownerThread == thisThread)
{
// this thread already owns this lock
switch (mutex->attr)
{
case gs_mutex_attr_normal:
// deadlock
assert(mutex->depth == 1);
AcquireSRWLockExclusive(&mutex->lock);
assert(false); // not reached
return 0;
case gs_mutex_attr_errorcheck:
// return deadlock error
assert(mutex->depth == 1);
return EDEADLK;
case gs_mutex_attr_recursive:
// recursive lock
mutex->depth++;
return 0;
}
}
// wait for another thread to release the lock
AcquireSRWLockExclusive(&mutex->lock);
assert(mutex->depth == 0);
mutex->depth = 1;
gs_atomic_store(&mutex->owner, thisThread);
return 0;
}
int
gs_mutex_trylock(gs_mutex_t *mutex)
{
DWORD thisThread = GetCurrentThreadId();
DWORD ownerThread;
if (TryAcquireSRWLockExclusive(&mutex->lock))
{
assert(mutex->depth == 0);
mutex->depth = 1;
gs_atomic_store(&mutex->owner, thisThread);
return 0;
}
// needs to be atomic because another thread can concurrently set it
ownerThread = gs_atomic_load(&mutex->owner);
if (ownerThread == thisThread && mutex->attr == gs_mutex_attr_recursive)
{
// this thread already owns this lock and it's recursive
assert(mutex->depth > 0);
mutex->depth++;
return 0;
}
// lock is taken
return EBUSY;
}
int
gs_mutex_unlock(gs_mutex_t *mutex)
{
switch (mutex->attr)
{
case gs_mutex_attr_normal:
break;
case gs_mutex_attr_errorcheck:
case gs_mutex_attr_recursive: {
// return error if lock is not held by this thread
DWORD thisThread = GetCurrentThreadId();
DWORD ownerThread = gs_atomic_load(&mutex->owner);
if (ownerThread != thisThread) {
return EPERM;
}
break;
}
}
if (mutex->attr == gs_mutex_attr_recursive && mutex->depth > 1)
{
// recursive lock releasing inner lock
mutex->depth--;
return 0;
}
else
{
assert(mutex->depth == 1);
mutex->depth = 0;
gs_atomic_store(&mutex->owner, 0);
ReleaseSRWLockExclusive(&mutex->lock);
return 0;
}
}
// NB: timeout specified in milliseconds relative to now
int
gs_cond_timedwait(gs_cond_t *cond, gs_mutex_t *mutex, DWORD millisecs)
{
int retVal = 0;
assert(mutex->depth == 1);
mutex->depth = 0;
gs_atomic_store(&mutex->owner, 0);
if (!SleepConditionVariableSRW(cond, &mutex->lock, millisecs, 0))
{
DWORD lastError = GetLastError();
if (lastError == ERROR_TIMEOUT) {
retVal = ETIMEDOUT;
} else {
retVal = lastError;
}
}
assert(mutex->depth == 0);
mutex->depth = 1;
gs_atomic_store(&mutex->owner, GetCurrentThreadId());
return retVal;
}
inline int
gs_cond_wait(gs_cond_t *cond, gs_mutex_t *mutex)
{
return gs_cond_timedwait(cond, mutex, INFINITE);
}
#endif /* GS_USE_WIN32_THREADS_AND_LOCKS */
/** </ignore>
*/
|