summaryrefslogtreecommitdiff
path: root/source/dng_pthread.cpp
blob: 03478565c21b9be51bf24a351e9a0227e19d0bcb (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
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
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
/*****************************************************************************/
// Copyright 2002-2008 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE:  Adobe permits you to use, modify, and distribute this file in
// accordance with the terms of the Adobe license agreement accompanying it.
/*****************************************************************************/

/* $Id: //mondo/dng_sdk_1_4/dng_sdk/source/dng_pthread.cpp#2 $ */ 
/* $DateTime: 2012/07/31 22:04:34 $ */
/* $Change: 840853 $ */
/* $Author: tknoll $ */

#include "dng_pthread.h"

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

#if qDNGThreadSafe

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

#include "dng_assertions.h"

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

#if qWinOS

#pragma warning(disable : 4786)

// Nothing in this file requires Unicode,
// However, CreateSemaphore has a path parameter
// (which is NULL always in this code) and thus
// does not work on Win98 if UNICODE is defined.
// So we force it off here.

#undef UNICODE
#undef _UNICODE

#include <windows.h>
#include <process.h>
#include <errno.h>
#include <memory>
#include <new>
#include <map>

#else

#include <sys/time.h>

#endif

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

#if qWinOS

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

namespace {
	struct waiter {
		struct waiter *prev;
		struct waiter *next;
		HANDLE semaphore;
		bool chosen_by_signal;
	};
}

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

struct dng_pthread_mutex_impl
{
	CRITICAL_SECTION lock;

	dng_pthread_mutex_impl()  { ::InitializeCriticalSection(&lock); }
	~dng_pthread_mutex_impl() { ::DeleteCriticalSection(&lock); }
	void Lock()				   { ::EnterCriticalSection(&lock); }
	void Unlock()			   { ::LeaveCriticalSection(&lock); }
private:
	dng_pthread_mutex_impl &operator=(const dng_pthread_mutex_impl &) { }
	dng_pthread_mutex_impl(const dng_pthread_mutex_impl &) { }
};

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

struct dng_pthread_cond_impl
{
	dng_pthread_mutex_impl lock;		// Mutual exclusion on next two variables
	waiter *head_waiter;			// List of threads waiting on this condition
	waiter *tail_waiter;			// Used to get FIFO, rather than LIFO, behavior for pthread_cond_signal 
	unsigned int broadcast_generation;	// Used as sort of a separator on broadcasts
										// saves having to walk the waiters list setting
										// each one's "chosen_by_signal" flag while the condition is locked

	dng_pthread_cond_impl() : head_waiter(NULL), tail_waiter(NULL), broadcast_generation(0) { }
	~dng_pthread_cond_impl() { } ;

// Non copyable
private:
	dng_pthread_cond_impl &operator=(const dng_pthread_cond_impl &) { }
	dng_pthread_cond_impl(const dng_pthread_cond_impl &) { }

};

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

namespace
{

	struct ScopedLock
	{
		dng_pthread_mutex_impl *mutex;

		ScopedLock(dng_pthread_mutex_impl *arg) : mutex(arg)
		{
			mutex->Lock();
		}
		ScopedLock(dng_pthread_mutex_impl &arg) : mutex(&arg)
		{
			mutex->Lock();
		}
		~ScopedLock()
		{
			mutex->Unlock();
		}
	private:
		ScopedLock &operator=(const ScopedLock &) { }
		ScopedLock(const ScopedLock &) { }
	};

	dng_pthread_mutex_impl validationLock;

	void ValidateMutex(dng_pthread_mutex_t *mutex)
	{
		if (*mutex != DNG_PTHREAD_MUTEX_INITIALIZER)
			return;

		ScopedLock lock(validationLock);

		if (*mutex == DNG_PTHREAD_MUTEX_INITIALIZER)
			dng_pthread_mutex_init(mutex, NULL);
	}

	void ValidateCond(dng_pthread_cond_t *cond)
	{
		if (*cond != DNG_PTHREAD_COND_INITIALIZER)
			return;

		ScopedLock lock(validationLock);

		if (*cond == DNG_PTHREAD_COND_INITIALIZER)
			dng_pthread_cond_init(cond, NULL);
	}

	DWORD thread_wait_sema_TLS_index;
	bool thread_wait_sema_inited = false;
	dng_pthread_once_t once_thread_TLS = DNG_PTHREAD_ONCE_INIT;

	void init_thread_TLS()
	{
		thread_wait_sema_TLS_index = ::TlsAlloc();
		thread_wait_sema_inited = true;
	}

	void finalize_thread_TLS()
	{
		if (thread_wait_sema_inited)
			{
			::TlsFree(thread_wait_sema_TLS_index);
			thread_wait_sema_inited = false;
			}
	}

	dng_pthread_mutex_impl primaryHandleMapLock;

	typedef std::map<DWORD, std::pair<HANDLE, void **> > ThreadMapType;

	// A map to make sure handles are freed and to allow returning a pointer sized result
	// even on 64-bit Windows.
	ThreadMapType primaryHandleMap;

	HANDLE GetThreadSemaphore()
	{
		dng_pthread_once(&once_thread_TLS, init_thread_TLS);

		HANDLE semaphore = ::TlsGetValue(thread_wait_sema_TLS_index);
		if (semaphore == NULL)
		{
			semaphore = ::CreateSemaphore(NULL, 0, 1, NULL);
			::TlsSetValue(thread_wait_sema_TLS_index, semaphore);
		}

		return semaphore;
	}

	void FreeThreadSemaphore()
	{
		if (thread_wait_sema_inited)
		{
			HANDLE semaphore = (HANDLE)::TlsGetValue(thread_wait_sema_TLS_index);

			if (semaphore != NULL)
			{
				::TlsSetValue(thread_wait_sema_TLS_index, NULL);
				::CloseHandle(semaphore);
			}
		}
	}

	struct trampoline_args
	{
		void *(*func)(void *);
		void *arg;
	};

	// This trampoline takes care of the return type being different
	// between pthreads thread funcs and Windows C lib thread funcs
	unsigned __stdcall trampoline(void *arg_arg)
	{
		trampoline_args *args_ptr = (trampoline_args *)arg_arg;
		trampoline_args args = *args_ptr;

		delete args_ptr;

		GetThreadSemaphore();
		
		void *result = args.func(args.arg);

		{
			ScopedLock lockMap(primaryHandleMapLock);

			ThreadMapType::iterator iter = primaryHandleMap.find(pthread_self());
			if (iter != primaryHandleMap.end())
				*iter->second.second = result;
		}

		FreeThreadSemaphore();

		return S_OK;
	}

}

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

extern "C" {

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

struct dng_pthread_attr_impl
	{
	size_t stacksize;
	};

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

int dng_pthread_attr_init(pthread_attr_t *attr)
	{
	dng_pthread_attr_impl *newAttrs;

	newAttrs = new (std::nothrow) dng_pthread_attr_impl;
	if (newAttrs == NULL)
		return -1; // ENOMEM;

	newAttrs->stacksize = 0;

	*attr = newAttrs;

	return 0;
	}

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

int dng_pthread_attr_destroy(pthread_attr_t *attr)
	{
	if (*attr == NULL)
		return -1; // EINVAL

	delete *attr;

	*attr = NULL;

	return 0;
	}

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

int dng_pthread_attr_setstacksize(dng_pthread_attr_t *attr, size_t stacksize)
	{
	if (attr == NULL || (*attr) == NULL)
		return -1; // EINVAL

	(*attr)->stacksize = stacksize;

	return 0;
	}

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

int dng_pthread_attr_getstacksize(const dng_pthread_attr_t *attr, size_t *stacksize)
	{
	if (attr == NULL || (*attr) == NULL || stacksize == NULL)
		return -1; // EINVAL

	*stacksize = (*attr)->stacksize;

	return 0;
	}

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

int dng_pthread_create(dng_pthread_t *thread, const pthread_attr_t *attrs, void * (*func)(void *), void *arg)
{
	try
	{
		uintptr_t result;
		unsigned threadID;
		std::auto_ptr<trampoline_args> args(new (std::nothrow) trampoline_args);
		std::auto_ptr<void *> resultHolder(new (std::nothrow) (void *));

		if (args.get() == NULL || resultHolder.get () == NULL)
			return -1; // ENOMEM

		args->func = func;
		args->arg = arg;

		size_t stacksize = 0;

		if (attrs != NULL)
			dng_pthread_attr_getstacksize (attrs, &stacksize);

		{
			ScopedLock lockMap(primaryHandleMapLock);

			result = _beginthreadex(NULL, (unsigned)stacksize, trampoline, args.get(), 0, &threadID);
			if (result == NULL)
				return -1; // ENOMEM
			args.release();

			std::pair<DWORD, std::pair<HANDLE, void **> > newMapEntry(threadID,
																	 std::pair<HANDLE, void **>((HANDLE)result, resultHolder.get ()));
			std::pair<ThreadMapType::iterator, bool> insertion = primaryHandleMap.insert(newMapEntry);

			// If there is a handle open on the thread, its ID should not be reused so assert that an insertion was made.
			DNG_ASSERT(insertion.second, "pthread emulation logic error");
		}


		resultHolder.release ();

		*thread = (dng_pthread_t)threadID;
		return 0;
	}
	catch (const std::bad_alloc &)
	{
		return -1;
	}
}

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

int dng_pthread_detach(dng_pthread_t thread)
{
	HANDLE primaryHandle;
	void **resultHolder = NULL;

	{
		ScopedLock lockMap(primaryHandleMapLock);

		ThreadMapType::iterator iter = primaryHandleMap.find(thread);
		if (iter == primaryHandleMap.end())
			return -1;

		primaryHandle = iter->second.first;

		// A join is waiting on the thread.
		if (primaryHandle == NULL)
			return -1;

		resultHolder = iter->second.second;

		primaryHandleMap.erase(iter);
	}

	delete resultHolder;

	if (!::CloseHandle(primaryHandle))
		return -1;

	return 0;
}

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

int dng_pthread_join(dng_pthread_t thread, void **result)
{
	bool found = false;
	HANDLE primaryHandle = NULL;
	void **resultHolder = NULL;

	ThreadMapType::iterator iter;

	{
		ScopedLock lockMap(primaryHandleMapLock);

		iter = primaryHandleMap.find(thread);
		found = iter != primaryHandleMap.end();
		if (found)
		{
			primaryHandle = iter->second.first;
			resultHolder = iter->second.second;

			// Set HANDLE to NULL to force any later join or detach to fail.
			iter->second.first = NULL;
		}
	}

	// This case can happens when joining a thread not created with pthread_create,
	// which is a bad idea, but it gets mapped to doing the join, but always returns NULL.
	if (!found)
		primaryHandle = ::OpenThread(SYNCHRONIZE|THREAD_QUERY_INFORMATION, FALSE, thread);

	if (primaryHandle == NULL)
		return -1;

	DWORD err;
	if (::WaitForSingleObject(primaryHandle, INFINITE) != WAIT_OBJECT_0)
	{
		err = ::GetLastError();
		return -1;
	}

	{
		ScopedLock lockMap(primaryHandleMapLock);

		if (iter != primaryHandleMap.end())
			primaryHandleMap.erase(iter);
	}

	::CloseHandle(primaryHandle);
	if (result != NULL && resultHolder != NULL)
		*result = *resultHolder;

	delete resultHolder;

	return 0;
}

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

dng_pthread_t dng_pthread_self()
{
	return (dng_pthread_t)::GetCurrentThreadId();
}

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

void dng_pthread_exit(void *result)
{
	{
		ScopedLock lockMap(primaryHandleMapLock);

		ThreadMapType::iterator iter = primaryHandleMap.find(pthread_self());
		if (iter != primaryHandleMap.end())
			*iter->second.second = result;
	}

	FreeThreadSemaphore();

	_endthreadex(S_OK);
}

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

int dng_pthread_mutex_init(dng_pthread_mutex_t *mutex, void * /* attrs */)
{
	dng_pthread_mutex_t result;
	try {
		result = new(dng_pthread_mutex_impl);
	} catch (const std::bad_alloc &)
	{
		return -1;
	}

	if (result == NULL)
		return -1;
	*mutex = result;
	return 0;
}

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

int dng_pthread_mutex_destroy(dng_pthread_mutex_t *mutex)
{
	if (*mutex == DNG_PTHREAD_MUTEX_INITIALIZER)
	{
		*mutex = NULL;
		return 0;
	}

	delete *mutex;
	*mutex = NULL;
	return 0;
}

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

int dng_pthread_cond_init(dng_pthread_cond_t *cond, void * /* attrs */)
{
	dng_pthread_cond_t result;
	try {
		result = new(dng_pthread_cond_impl);
	} catch (const std::bad_alloc &)
	{
		return -1;
	}

	if (result == NULL)
		return -1;
	*cond = result;
	return 0;
}

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

int dng_pthread_cond_destroy(dng_pthread_cond_t *cond)
{
	if (*cond == DNG_PTHREAD_COND_INITIALIZER)
	{
		*cond = NULL;
		return 0;
	}

	delete *cond;
	*cond = NULL;
	return 0;
}

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

int dng_pthread_mutexattr_init(dng_pthread_mutexattr_t* mutexattr)
{
	return 0;
}

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

int dng_pthread_mutexattr_settype(dng_pthread_mutexattr_t* mutexattr, int type)
{
	return 0;
}

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

int dng_pthread_mutex_lock(dng_pthread_mutex_t *mutex)
{
	ValidateMutex(mutex);
	(*mutex)->Lock();
	return 0;
}

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

int dng_pthread_mutex_unlock(dng_pthread_mutex_t *mutex)
{
	ValidateMutex(mutex);
	(*mutex)->Unlock();
	return 0;
}

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

static int cond_wait_internal(dng_pthread_cond_t *cond, dng_pthread_mutex_t *mutex, int timeout_milliseconds)
{
	dng_pthread_cond_impl &real_cond = **cond;
	dng_pthread_mutex_impl &real_mutex = **mutex;

	waiter this_wait;
	HANDLE semaphore = GetThreadSemaphore();
	int my_generation; // The broadcast generation this waiter is in

	{
		this_wait.next = NULL;
		this_wait.semaphore = semaphore;
		this_wait.chosen_by_signal = 0;

		ScopedLock lock1(real_cond.lock);

		// Add this waiter to the end of the list.
		this_wait.prev = real_cond.tail_waiter;
		if (real_cond.tail_waiter != NULL)
			real_cond.tail_waiter->next = &this_wait;
		real_cond.tail_waiter = &this_wait;

		// If the list was empty, set the head of the list to this waiter.
		if (real_cond.head_waiter == NULL)
			real_cond.head_waiter = &this_wait;

		// Note which broadcast generation this waiter belongs to.
		my_generation = real_cond.broadcast_generation;
	}

	real_mutex.Unlock();

	DWORD result = ::WaitForSingleObject(semaphore, timeout_milliseconds);

	if (result == WAIT_TIMEOUT)
	{
		// If the wait timed out, this thread is likely still on the waiters list
		// of the condition. However, there is a race in that the thread may have been
		// signaled or broadcast between when WaitForSingleObject decided
		// we had timed out and this code running.

		bool mustConsumeSemaphore = false;
		{
			ScopedLock lock2(real_cond.lock);

			bool chosen_by_signal = this_wait.chosen_by_signal;
			bool chosen_by_broadcast = my_generation != real_cond.broadcast_generation;

			if (chosen_by_signal || chosen_by_broadcast)
				mustConsumeSemaphore = true;
			else
			{
				// Still on waiters list. Remove this waiter from list.
				if (this_wait.next != NULL)
					this_wait.next->prev = this_wait.prev;
				else
					real_cond.tail_waiter = this_wait.prev;

				if (this_wait.prev != NULL)
					this_wait.prev->next = this_wait.next;
				else
					real_cond.head_waiter = this_wait.next;
			}
		}

		if (mustConsumeSemaphore)
		{
			::WaitForSingleObject(semaphore, INFINITE);
			result = WAIT_OBJECT_0;
		}
	}
	else
		DNG_ASSERT (result == WAIT_OBJECT_0, "pthread emulation logic error");

	// reacquire the mutex
	real_mutex.Lock();

	return (result == WAIT_TIMEOUT) ? DNG_ETIMEDOUT : 0;
}

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

int dng_pthread_cond_wait(dng_pthread_cond_t *cond, dng_pthread_mutex_t *mutex)
{
	ValidateCond(cond);

	return cond_wait_internal(cond, mutex, INFINITE);	
}

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

int dng_pthread_cond_timedwait(dng_pthread_cond_t *cond, dng_pthread_mutex_t *mutex, struct dng_timespec *latest_time)
{
	ValidateCond(cond);
	
	struct dng_timespec sys_timespec;
	
	dng_pthread_now (&sys_timespec);

	__int64 sys_time  = (__int64)sys_timespec.tv_sec * 1000000000 + sys_timespec.tv_nsec;
	__int64 lock_time = (__int64)latest_time->tv_sec * 1000000000 + latest_time->tv_nsec;

	int wait_millisecs = (int)((lock_time - sys_time + 500000) / 1000000);
	
	if (wait_millisecs < 0)
		wait_millisecs = 0;

	return cond_wait_internal(cond, mutex, wait_millisecs);	
}

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

int dng_pthread_cond_signal(dng_pthread_cond_t *cond)
{
	ValidateCond(cond);

	waiter *first;
	dng_pthread_cond_impl &real_cond = **cond;

	{
		ScopedLock lock(real_cond.lock);

		first = real_cond.head_waiter;
		if (first != NULL)
		{
			if (first->next != NULL)
				first->next->prev = NULL;
			else
				real_cond.tail_waiter = NULL; // Or first->prev, which is always NULL in this case

			first->chosen_by_signal = true;

			real_cond.head_waiter = first->next;
		}
	}

	if (first != NULL)
		::ReleaseSemaphore(first->semaphore, 1, NULL);

	return 0;
}

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

int dng_pthread_cond_broadcast(dng_pthread_cond_t *cond)
{
	ValidateCond(cond);

	waiter *first;
	dng_pthread_cond_impl &real_cond = **cond;

	{
		ScopedLock lock(real_cond.lock);

		first = real_cond.head_waiter;
		real_cond.head_waiter = NULL;
		real_cond.tail_waiter = NULL;

		real_cond.broadcast_generation++;
	}

	while (first != NULL)
	{
		waiter *next = first->next;
		::ReleaseSemaphore(first->semaphore, 1, NULL);
		first = next;
	}

	return 0;
}

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

int dng_pthread_once(dng_pthread_once_t *once, void (*init_func)())
{
	if (once == NULL || init_func == NULL)
		return EINVAL;

	if (once->inited)
		return 0;

	if (::InterlockedIncrement(&once->semaphore) == 0)
	{
		init_func();
		once->inited = 1;
	}
	else
	{
		while (!once->inited)
			Sleep(0);
	}

	return 0;
}

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

int dng_pthread_key_create(dng_pthread_key_t * key, void (*destructor) (void *))
{
	if (destructor != NULL)
		return -1;

	DWORD result = ::TlsAlloc();
	if (result == TLS_OUT_OF_INDEXES)
		return -1;
	*key = (unsigned long)result;
	return 0;
}

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

int dng_pthread_key_delete(dng_pthread_key_t key)
{
	if (::TlsFree((DWORD)key))
		return 0;
	return -1;
}

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

int dng_pthread_setspecific(dng_pthread_key_t key, const void *value)
{
	if (::TlsSetValue((DWORD)key, const_cast<void *>(value)))
		return 0;
	return -1;
}

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

void *dng_pthread_getspecific(dng_pthread_key_t key)
{
	return ::TlsGetValue((DWORD)key);
}

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

namespace {
	struct rw_waiter {
		struct rw_waiter *prev;
		struct rw_waiter *next;
		HANDLE semaphore;
		bool is_writer;
	};
}

struct dng_pthread_rwlock_impl
{
	dng_pthread_mutex_impl mutex;
	
	rw_waiter *head_waiter;
	rw_waiter *tail_waiter;
	
	unsigned long readers_active;
	unsigned long writers_waiting;
	bool writer_active;

	dng_pthread_cond_impl read_wait;
	dng_pthread_cond_impl write_wait;

	dng_pthread_rwlock_impl ()
		: mutex ()
		, head_waiter (NULL)
		, tail_waiter (NULL)
		, readers_active (0)
		, writers_waiting (0)
		, read_wait ()
		, write_wait ()
		, writer_active (false)
	{
	}

	~dng_pthread_rwlock_impl ()
	{
	}

	void WakeHeadWaiter ()
	{
		HANDLE semaphore = head_waiter->semaphore;

		head_waiter = head_waiter->next;
		if (head_waiter == NULL)
			tail_waiter = NULL;

		::ReleaseSemaphore(semaphore, 1, NULL);
	}

};

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

int dng_pthread_rwlock_init(dng_pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *attrs)
{
	dng_pthread_rwlock_impl *newRWLock;

	newRWLock = new (std::nothrow) dng_pthread_rwlock_impl;
	if (newRWLock == NULL)
		return -1; // ENOMEM;

	*rwlock = newRWLock;

	return 0;
}

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

int dng_pthread_rwlock_destroy(dng_pthread_rwlock_t *rwlock)
{
	dng_pthread_rwlock_impl &real_rwlock = **rwlock;

	{
		ScopedLock lock (real_rwlock.mutex);

		if (real_rwlock.head_waiter != NULL ||
			real_rwlock.readers_active != 0 ||
			real_rwlock.writers_waiting != 0 ||
			real_rwlock.writer_active)
			return -1; // EBUSY
	}

	delete *rwlock;
	*rwlock = NULL;
	return 0;
}

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

#define CHECK_RWLOCK_STATE(real_rwlock) \
	DNG_ASSERT (!real_rwlock.writer_active || real_rwlock.readers_active == 0, "dng_pthread_rwlock_t logic error")

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

int dng_pthread_rwlock_rdlock(dng_pthread_rwlock_t *rwlock)
{
	dng_pthread_rwlock_impl &real_rwlock = **rwlock;

	struct rw_waiter this_wait;
	bool doWait = false;;
	int result = 0;
	HANDLE semaphore=NULL;

		{

		ScopedLock lock (real_rwlock.mutex);

		CHECK_RWLOCK_STATE (real_rwlock);

		if (real_rwlock.writers_waiting > 0 || real_rwlock.writer_active)
		{
			semaphore = GetThreadSemaphore();

			this_wait.next = NULL;
			this_wait.semaphore = semaphore;
			this_wait.is_writer = false;

			// Add this waiter to the end of the list.
			this_wait.prev = real_rwlock.tail_waiter;
			if (real_rwlock.tail_waiter != NULL)
				real_rwlock.tail_waiter->next = &this_wait;
			real_rwlock.tail_waiter = &this_wait;

			// If the list was empty, set the head of the list to this waiter.
			if (real_rwlock.head_waiter == NULL)
				real_rwlock.head_waiter = &this_wait;

			doWait = true;
		}
		else
			real_rwlock.readers_active++;
	}

	if (result == 0 && doWait)
		result = (WaitForSingleObject(semaphore, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;

	return result;
}

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

int dng_pthread_rwlock_tryrdlock(dng_pthread_rwlock_t *rwlock)
{
	dng_pthread_rwlock_impl &real_rwlock = **rwlock;

	ScopedLock lock (real_rwlock.mutex);

	CHECK_RWLOCK_STATE (real_rwlock);

	if (real_rwlock.writers_waiting == 0 && !real_rwlock.writer_active)
	{
		real_rwlock.readers_active++;
		return 0;
	}

	return -1;
}

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

int dng_pthread_rwlock_trywrlock(dng_pthread_rwlock_t *rwlock)
{
	dng_pthread_rwlock_impl &real_rwlock = **rwlock;

	ScopedLock lock (real_rwlock.mutex);

	CHECK_RWLOCK_STATE (real_rwlock);

	if (real_rwlock.readers_active == 0 &&
		real_rwlock.writers_waiting == 0 &&
		!real_rwlock.writer_active)
		{
		real_rwlock.writer_active = true;
		return 0;
		}

	return -1;
}

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

int dng_pthread_rwlock_unlock(dng_pthread_rwlock_t *rwlock)
	{
	dng_pthread_rwlock_impl &real_rwlock = **rwlock;

	int result = 0;

	ScopedLock lock (real_rwlock.mutex);

	CHECK_RWLOCK_STATE (real_rwlock);

	if (real_rwlock.readers_active > 0)
		--real_rwlock.readers_active;
	else
		real_rwlock.writer_active = false;

	while (real_rwlock.head_waiter != NULL)
	{
		if (real_rwlock.head_waiter->is_writer)
		{
			if (real_rwlock.readers_active == 0)
			{
			    real_rwlock.writers_waiting--;
			    real_rwlock.writer_active = true;
			    real_rwlock.WakeHeadWaiter ();
			}

			break;
		}
		else
		{
			++real_rwlock.readers_active;
			real_rwlock.WakeHeadWaiter ();
		}
	}

	return result;
	}

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

int dng_pthread_rwlock_wrlock(dng_pthread_rwlock_t *rwlock)
	{
	dng_pthread_rwlock_impl &real_rwlock = **rwlock;

	int result = 0;
	struct rw_waiter this_wait;
	HANDLE semaphore=NULL;
	bool doWait = false;

	{
		ScopedLock lock (real_rwlock.mutex);

		CHECK_RWLOCK_STATE (real_rwlock);

		if (real_rwlock.readers_active ||
			real_rwlock.writers_waiting ||
			real_rwlock.writer_active)
			{
			semaphore = GetThreadSemaphore();

			this_wait.next = NULL;
			this_wait.semaphore = semaphore;
			this_wait.is_writer = true;

			// Add this waiter to the end of the list.
			this_wait.prev = real_rwlock.tail_waiter;
			if (real_rwlock.tail_waiter != NULL)
				real_rwlock.tail_waiter->next = &this_wait;
			real_rwlock.tail_waiter = &this_wait;

			// If the list was empty, set the head of the list to this waiter.
			if (real_rwlock.head_waiter == NULL)
				real_rwlock.head_waiter = &this_wait;

			real_rwlock.writers_waiting++;

			doWait = true;
		}
		else
			real_rwlock.writer_active = true;
	}

	if (result == 0 && doWait)
		result = (WaitForSingleObject(semaphore, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;

	return result;
	}

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

void dng_pthread_disassociate()
{
	FreeThreadSemaphore();
}

void dng_pthread_terminate()
	{
	finalize_thread_TLS();
	}

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

}	// extern "C"

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

#endif

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

int dng_pthread_now (struct timespec *now)
	{
	
	if (now == NULL)
		return -1; // EINVAL
		
	#if qWinOS

	FILETIME ft;
	::GetSystemTimeAsFileTime(&ft);

	__int64 sys_time = ((__int64)ft.dwHighDateTime << 32) + ft.dwLowDateTime;

	#define SecsFrom1601To1970 11644473600
	
	sys_time -= SecsFrom1601To1970 * 10000000LL;
	
	sys_time *= 100;	// Convert from 100ns to 1ns units

	now->tv_sec  = (long)(sys_time / 1000000000);
	now->tv_nsec = (long)(sys_time % 1000000000);
	
	#else
	
	struct timeval tv;

	if (gettimeofday (&tv, NULL) != 0)
		return errno;

	now->tv_sec  = tv.tv_sec;
	now->tv_nsec = tv.tv_usec * 1000;

	#endif

	return 0;
	
	}

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

#endif // qDNGThreadSafe

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