summaryrefslogtreecommitdiff
path: root/plugins/Dbx_tree/src/MREWSync.cpp
blob: 6e08be64755c28e86c836c1a3905892a6fc47311 (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
/*

dbx_tree: tree database driver for Miranda IM

Copyright 2007-2010 Michael "Protogenes" Kunz,

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#include "MREWSync.h"
#include <assert.h>
#include "intrinsics.h"

#if defined(MREW_DO_DEBUG_LOGGING) && (defined(DEBUG) || defined(_DEBUG))
	#include <stdio.h>
#endif


///////////////////////////////////////////////////////////////////////////////////////////////////
// +------------+---------------+---------------+------------+---------------+
// | ReaderBusy | ReaderWaiting | WriterWaiting | WriterBusy | UseOddReader? |
// +------------+---------------+---------------+------------+---------------+
//     63..44         43..24          23..4            3             0
///////////////////////////////////////////////////////////////////////////////////////////////////
#define isWriterBusy(Sentinel)    ((Sentinel) & 0x0000000000000008ui64)
#define isWriterWaiting(Sentinel) ((Sentinel) & 0x0000000000fffff0ui64)
#define isReaderWaiting(Sentinel) ((Sentinel) & 0x00000fffff000000ui64)
#define isReaderBusy(Sentinel)    ((Sentinel) & 0xfffff00000000000ui64)

#define countWriterWaiting(Sentinel) (((Sentinel) & 0x0000000000fffff0ui64) >>  4)
#define countReaderWaiting(Sentinel) (((Sentinel) & 0x00000fffff000000ui64) >> 24)
#define countReaderBusy(Sentinel)    (((Sentinel) & 0xfffff00000000000ui64) >> 44)

#define WriterBusy    (1ui64 <<  3)
#define WriterWaiting (1ui64 <<  4)
#define ReaderWaiting (1ui64 << 24)
#define ReaderBusy    (1ui64 << 44)

#define isUseOddReader(Sentinel) ((Sentinel) & 1)
#define useOddReader             (1ui64)

CMultiReadExclusiveWriteSynchronizer::CMultiReadExclusiveWriteSynchronizer(void)
: tls(),
	m_Sentinel(0)
{
	m_ReadSignal[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
	m_ReadSignal[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
	m_WriteSignal   = CreateEvent(NULL, FALSE, FALSE, NULL);
	m_WriterID = 0;
	m_WriteRecursion = 0;
	m_Revision = 0;
}

CMultiReadExclusiveWriteSynchronizer::~CMultiReadExclusiveWriteSynchronizer(void)
{
	BeginWrite();
	CloseHandle(m_WriteSignal);
	CloseHandle(m_ReadSignal[0]);
	CloseHandle(m_ReadSignal[1]);
}

void CMultiReadExclusiveWriteSynchronizer::BeginRead()
{
	unsigned long id = GetCurrentThreadId();
	unsigned & reccount(tls.Open(this, 0));
	
	reccount++;
	if ((m_WriterID != id) && (reccount == 1))
	{
		int64_t old;
		int64_t newvalue;

		do {
			old = m_Sentinel;
			if (isWriterBusy(old))
				newvalue = old + ReaderBusy; // writer has lock -> we are going to enter after he leaves -> we are busy but have to wait
			else if (isWriterWaiting(old))
				newvalue = old + ReaderWaiting; // writer is waiting for lock -> don't set myself busy as he waits for all readers to leave lock
			else 
				newvalue = old + ReaderBusy; // no writer in sight, just take lock
		
		} while (CMPXCHG_64(m_Sentinel, newvalue, old) != old);


		if (isWriterBusy(old) || isWriterWaiting(old))
		{
			if (isUseOddReader(old))
				WaitForSingleObject(m_ReadSignal[1], INFINITE);
			else
				WaitForSingleObject(m_ReadSignal[0], INFINITE);
		}
	}
}
void CMultiReadExclusiveWriteSynchronizer::EndRead()
{
	unsigned long id = GetCurrentThreadId();
	unsigned & reccount(tls.Open(this, 1));
	reccount--;

	if ((reccount == 0) && (m_WriterID != id))
	{
		int64_t old;
		int64_t newvalue;

		do {
			old = m_Sentinel;
			if ((countReaderBusy(old) == 1) && isWriterWaiting(old))
			{ // give control to the writer... move waiting readers to busy (but blocked)
				newvalue = old - WriterWaiting + WriterBusy - ReaderBusy + countReaderWaiting(old) * (ReaderBusy - ReaderWaiting);
			} else {
				newvalue = old - ReaderBusy;
			}
		} while (CMPXCHG_64(m_Sentinel, newvalue, old) != old);

		if ((countReaderBusy(old) == 1) && isWriterWaiting(old))
		{
			SetEvent(m_WriteSignal);
		}
	}

	if (reccount == 0)
		tls.Remove(this);
}
bool CMultiReadExclusiveWriteSynchronizer::BeginWrite()
{
	unsigned long id = GetCurrentThreadId();
	unsigned * reccount = tls.Find(this);
	bool res = true;

	if (m_WriterID != id)
	{
		int64_t old;
		int64_t newvalue;
		unsigned int oldrevision = m_Revision;

		if (reccount) // upgrade our readlock
		{
			do {
				old = m_Sentinel;
				// isWriterBusy cannot happen because we have a readlock, so we ignore it
				if (countReaderBusy(old) > 1) // there is another reader.. we have to wait for him. set arriving readers to waiting state
				{
					newvalue = old + WriterWaiting - ReaderBusy;
				} else if (isWriterWaiting(old)) // there is another writer waiting, who arrived earlier. we will sign him in and wait. we are the last reader, so we have to update the sentinel
				{
					newvalue = old + WriterBusy - ReaderBusy + countReaderWaiting(old) * (ReaderBusy - ReaderWaiting);
				} else { // nobody is busy, we want the lock
					newvalue = old + WriterBusy - ReaderBusy;
				}
			} while (CMPXCHG_64(m_Sentinel, newvalue, old) != old);

			if (countReaderBusy(old) > 1)
			{
				WaitForSingleObject(m_WriteSignal, INFINITE); // someone woke me up... he had to take care of all state changes of the sentinel
			} else if (isWriterWaiting(old)) // we will wait for the other writer, as we are the last reader, we have to wake him up
			{
				SetEvent(m_WriteSignal);
				Sleep(0); // yield thread trying to keep FIFO order
				WaitForSingleObject(m_WriteSignal, INFINITE); // someone woke me up... he had to take care of all state changes of the sentinel
			}
		} else { // gain write lock
			do {
				old = m_Sentinel;
				if (isWriterBusy(old)) // there is a writer.. we have to wait for him
				{
					newvalue = old + WriterWaiting;
				} else if (isReaderBusy(old)) // there is a reader.. we have to wait for him. set arriving readers to waiting state
				{
					newvalue = old + WriterWaiting;
				} else if (isWriterWaiting(old)) // there is another writer waiting, who arrived earlier. we will wait
				{
					newvalue = old + WriterWaiting;
				} else { // nobody is busy, we want the lock
					newvalue = old + WriterBusy;
				}
			} while (CMPXCHG_64(m_Sentinel, newvalue, old) != old);

			if (isWriterBusy(old) || isReaderBusy(old) || isWriterWaiting(old))
			{
				WaitForSingleObject(m_WriteSignal, INFINITE); // someone woke me up... he had to take care of all state changes of the sentinel
			}
		}
		res = (oldrevision == (INC_32(m_Revision) - 1));

		m_WriterID = id;
	}
	m_WriteRecursion++;

	return res;
}

bool CMultiReadExclusiveWriteSynchronizer::EndWrite()
{
	unsigned long id = GetCurrentThreadId();
	unsigned * reccount = tls.Find(this);

	m_WriteRecursion--;

	if (m_WriteRecursion == 0)
	{
		int64_t old;
		int64_t newvalue;

		m_WriterID = 0;

		if (isUseOddReader(m_Sentinel)) // reset upcoming signal
			ResetEvent(m_ReadSignal[0]);
		else
			ResetEvent(m_ReadSignal[1]);

		if (reccount) // downgrade to reader lock
		{
			do {
				old = m_Sentinel;
				newvalue = (old ^ useOddReader) - WriterBusy + ReaderBusy; // single case... we are a waiting reader and we will keep control of the lock
			} while (CMPXCHG_64(m_Sentinel, newvalue, old) != old);

			if (isUseOddReader(old)) // allow additional readers to pass
				SetEvent(m_ReadSignal[1]);
			else
				SetEvent(m_ReadSignal[0]);

		} else {

			do {
				old = m_Sentinel;
				if (isReaderBusy(old)) // give control to waiting readers
				{
					newvalue = (old ^ useOddReader) - WriterBusy;
				} else if (isWriterWaiting(old)) // no reader arrived while i was working... give control to next writer 
				{
					newvalue = (old ^ useOddReader) - WriterWaiting;
				} else { // nobody else is there... just close lock
					newvalue = (old ^ useOddReader) - WriterBusy;
				}
			} while (CMPXCHG_64(m_Sentinel, newvalue, old) != old);

			if (isReaderBusy(old)) // release waiting readers
			{
				if (isUseOddReader(old))
					SetEvent(m_ReadSignal[1]);
				else
					SetEvent(m_ReadSignal[0]);
			} else if (isWriterWaiting(old))
			{
				SetEvent(m_WriteSignal);
			}
		}
		return true;
	}

	return false;
}

bool CMultiReadExclusiveWriteSynchronizer::TryBeginWrite()
{
	unsigned long id = GetCurrentThreadId();
	unsigned * reccount = tls.Find(this); 

	if (m_WriterID != id)
	{
		int64_t old;
		int64_t newvalue;
		unsigned int oldrevision = m_Revision;

		if (reccount) // upgrade our readlock
		{
			do {
				old = m_Sentinel;
				// isWriterBusy cannot happen because we have a readlock, so we ignore it
				if (countReaderBusy(old) > 1) // there is another reader.. we have to wait for him. set arriving readers to waiting state
				{
					return false;
				} else if (isWriterWaiting(old)) // there is another writer waiting, who arrived earlier. we will sign him in and wait. we are the last reader, so we have to update the sentinel
				{
					return false;
				} else { // nobody is busy, we want the lock
					newvalue = old + WriterBusy - ReaderBusy;
				}
			} while (CMPXCHG_64(m_Sentinel, newvalue, old) != old);

		} else { // gain write lock
			do {
				old = m_Sentinel;
				if (isWriterBusy(old)) // there is a writer.. we have to wait for him
				{
					return false;
				} else if (isReaderBusy(old)) // there is a reader.. we have to wait for him. set arriving readers to waiting state
				{
					return false;
				} else if (isWriterWaiting(old)) // there is another writer waiting, who arrived earlier. we will wait
				{
					return false;
				} else { // nobody is busy, we want the lock
					newvalue = old + WriterBusy;
				}
			} while (CMPXCHG_64(m_Sentinel, newvalue, old) != old);
		}
		INC_32(m_Revision);

		m_WriterID = id;
	}
	m_WriteRecursion++;

	return true;
}

unsigned int CMultiReadExclusiveWriteSynchronizer::Waiting()
{
	int64_t old = m_Sentinel;
	if (isWriterBusy(old))
	{ // cast is safe, we don't loose data because these fields are max 20 bits
		return static_cast<unsigned int>(countReaderBusy(old) + countReaderWaiting(old) + countWriterWaiting(old));
	} else {
		return static_cast<unsigned int>(countReaderWaiting(old) + countWriterWaiting(old));
	}
};