summaryrefslogtreecommitdiff
path: root/plugins/YAMN/src/synchro.cpp
blob: 84cc4cece05d7e584456d70a0e714763ad349898 (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
/*
 * This code implements synchronization objects code between threads. If you want, you can include it to your
 * code. This file is not dependent on any other external code (functions)
 *
 * (c) majvan 2002-2004
 */

#include "yamn.h"

// Initializes a SWMRG structure. This structure must be 
// initialized before any writer or reader threads attempt
// to wait on it.
// The structure must be allocated by the application and 
// the structure's address is passed as the first parameter.
// The lpszName parameter is the name of the object. Pass
// NULL if you do not want to share the object.
BOOL WINAPI SWMRGInitialize(PSWMRG pSWMRG,TCHAR *Name);

// Deletes the system resources associated with a SWMRG 
// structure. The structure must be deleted only when
// no writer or reader threads in the calling process
// will wait on it.
void WINAPI SWMRGDelete(PSWMRG pSWMRG);

// A writer thread calls this function to know when 
// it can successfully write to the shared data.
// returns WAIT_FINISH when we are in write-access or WAIT_FAILED
// when event about quick finishing is set (or when system returns fail when waiting for synchro object)
DWORD WINAPI SWMRGWaitToWrite(PSWMRG pSWMRG,DWORD dwTimeout);

// A writer thread calls this function to let other threads
// know that it no longer needs to write to the shared data.
void WINAPI SWMRGDoneWriting(PSWMRG pSWMRG);

// A reader thread calls this function to know when 
// it can successfully read the shared data.
// returns WAIT_FINISH when we are in read-access or WAIT_FAILED
// when event about quick finishing is set (or when system returns fail when waiting for synchro object)
DWORD WINAPI SWMRGWaitToRead(PSWMRG pSWMRG, DWORD dwTimeout);

// A reader thread calls this function to let other threads
// know when it no longer needs to read the shared data.
void WINAPI SWMRGDoneReading(PSWMRG pSWMRG);

// WaitToReadFcn
// is used to wait for read access with SWMRG SO, but it also increments counter if successfull
// returns WAIT_FAILED or WAIT_FINISH
// when WAIT_FAILED, we should not begin to access datas, we are not in read-access mode
DWORD WINAPI WaitToReadFcn(PSWMRG SObject);

// WriteDoneFcn
// is used to release read access with SWMRG SO, but it also decrements counter if successfull
void WINAPI ReadDoneFcn(PSWMRG SObject);

// This functions is for export purposes
// Plugin can call this function to manage SCOUNTER synchronization object

// Gets number value stored in SCOUNTER SO
// Note you must not read the number from memory directly, because
// CPU can stop reading thread when it has read HI-Word, then another thread
// can change the value and then OS starts the previous thread, that reads the
// LO-WORD of DWORD. And the return value HI+LO-WORD is corrupted
DWORD WINAPI SCGetNumberFcn(PSCOUNTER SCounter);

// Increments SCOUNTER and unsets event
// Returns Number after incrementing
DWORD WINAPI SCIncFcn(PSCOUNTER SCounter);

// Decrements SCOUNTER and sets event if zero
// Returns Number after decrementing
DWORD WINAPI SCDecFcn(PSCOUNTER SCounter);

struct CExportedFunctions SynchroExportedFcn[]=
{
	{YAMN_WAITTOWRITEID,(void *)WaitToWriteFcn},
	{YAMN_WRITEDONEID,(void *)WriteDoneFcn},
	{YAMN_WAITTOREADID,(void *)WaitToReadFcn},
	{YAMN_READDONEID,(void *)ReadDoneFcn},
	{YAMN_SCGETNUMBERID,(void *)SCGetNumberFcn},
	{YAMN_SCINCID,(void *)SCIncFcn},
	{YAMN_SCDECID,(void *)SCDecFcn},
};

//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------

void WINAPI SWMRGDelete(PSWMRG pSWMRG)
{
// Destroys any synchronization objects that were 
// successfully created.
	if (NULL != pSWMRG->hEventNoWriter)
		CloseHandle(pSWMRG->hEventNoWriter);
	if (NULL != pSWMRG->hEventNoReaders)
		CloseHandle(pSWMRG->hEventNoReaders);
	if (NULL != pSWMRG->hSemNumReaders)
		CloseHandle(pSWMRG->hSemNumReaders);
	if (NULL != pSWMRG->hFinishEV)
		CloseHandle(pSWMRG->hFinishEV);
}

BOOL WINAPI SWMRGInitialize(PSWMRG pSWMRG,TCHAR *Name)
{
	pSWMRG->hEventNoWriter=NULL;
	pSWMRG->hEventNoReaders=NULL;
	pSWMRG->hSemNumReaders=NULL;
	pSWMRG->hFinishEV=NULL;

// Creates the automatic-reset event that is signalled when 
// no writer threads are writing.
// Initially no reader threads are reading.
	if (Name != NULL)
		Name[0]=(TCHAR)'W';
	pSWMRG->hEventNoWriter=CreateEvent(NULL,FALSE,TRUE,Name);

// Creates the manual-reset event that is signalled when 
// no reader threads are reading.
// Initially no reader threads are reading.
	if (Name != NULL)
		Name[0]=(TCHAR)'R';
	pSWMRG->hEventNoReaders=CreateEvent(NULL,TRUE,TRUE,Name);

// Initializes the variable that indicates the number of 
// reader threads that are reading.
// Initially no reader threads are reading.
	if (Name != NULL)
		Name[0]=(TCHAR)'C';
	pSWMRG->hSemNumReaders=CreateSemaphore(NULL,0,0x7FFFFFFF,Name);

	if (Name != NULL)
		Name[0]=(TCHAR)'F';
	pSWMRG->hFinishEV=CreateEvent(NULL,TRUE,FALSE,Name);

// If a synchronization object could not be created,
// destroys any created objects and return failure.
	if ((NULL==pSWMRG->hEventNoWriter) || (NULL==pSWMRG->hEventNoReaders) || (NULL==pSWMRG->hSemNumReaders) || (NULL==pSWMRG->hFinishEV))
	{
		SWMRGDelete(pSWMRG);
		return FALSE;
	}
	return TRUE;
}

DWORD WINAPI SWMRGWaitToWrite(PSWMRG pSWMRG,DWORD dwTimeout)
{
	DWORD dw; 
	HANDLE aHandles[2];

// We can write if the following are true:
// 1. No other threads are writing.
// 2. No threads are reading.
// But first we have to know if SWMRG structure is not about to delete
	aHandles[0]=pSWMRG->hEventNoWriter;
	aHandles[1]=pSWMRG->hEventNoReaders;
	if (WAIT_OBJECT_0==(dw=WaitForSingleObject(pSWMRG->hFinishEV,0)))
		return WAIT_FINISH;
	if (WAIT_FAILED==dw)
		return dw;
	dw=WaitForMultipleObjects(2,aHandles,TRUE,dwTimeout);
// if a request to delete became later, we should not catch it. Try once more to ask if account is not about to delete
	if ((dw != WAIT_FAILED) && (WAIT_OBJECT_0==(WaitForSingleObject(pSWMRG->hFinishEV,0))))
	{
		SetEvent(pSWMRG->hEventNoWriter);
		return WAIT_FINISH;
	}

// This thread can write to the shared data.
// Automatic event for NoWriter sets hEventNoWriter to nonsignaled after WaitForMultipleObject

// Because a writer thread is writing, the Event 
// should not be reset. This stops other 
// writers and readers.
	return dw;
}

void WINAPI SWMRGDoneWriting(PSWMRG pSWMRG)
// Presumably, a writer thread calling this function has
// successfully called WaitToWrite. This means that we
// do not have to wait on any synchronization objects 
// here because the writer already owns the Event.
{
// Allow other writer/reader threads to use
// the SWMRG synchronization object.
	SetEvent(pSWMRG->hEventNoWriter);
}

DWORD WINAPI SWMRGWaitToRead(PSWMRG pSWMRG, DWORD dwTimeout)
{
	DWORD dw; 
	LONG lPreviousCount;

// We can read if no threads are writing.
// And there's not request to delete structure
	if (WAIT_OBJECT_0==(dw=WaitForSingleObject(pSWMRG->hFinishEV,0)))
		return WAIT_FINISH;
	if (WAIT_FAILED==dw)
		return dw;
	dw=WaitForSingleObject(pSWMRG->hEventNoWriter, dwTimeout);
// if a request to delete became later, we should not catch it. Try once more to ask if account is not about to delete
	if ((dw != WAIT_FAILED) && (WAIT_OBJECT_0==(WaitForSingleObject(pSWMRG->hFinishEV,0))))
	{
		SetEvent(pSWMRG->hEventNoWriter);
		return WAIT_FINISH;
	}

	if (dw==WAIT_OBJECT_0)
	{
	// This thread can read from the shared data.
	// Increment the number of reader threads.
	// But there can't be more than one thread incrementing readers,
	// so this is why we use semaphore.
		ReleaseSemaphore(pSWMRG->hSemNumReaders,1,&lPreviousCount);
		if (lPreviousCount==0)
			// If this is the first reader thread, 
			// set event to reflect this. Other reader threads can read, no writer thread can write.
			ResetEvent(pSWMRG->hEventNoReaders);

		// Allow other writer/reader threads to use
		// the SWMRG synchronization object. hEventNoWrite is still non-signaled
		// (it looks like writer is processing thread, but it is not true)
		SetEvent(pSWMRG->hEventNoWriter);
	}

	return(dw);
}

void WINAPI SWMRGDoneReading(PSWMRG pSWMRG)
{
	HANDLE aHandles[2];
	LONG lNumReaders;

// We can stop reading if the events are available,
// but when we stop reading we must also decrement the
// number of reader threads.
	aHandles[0]=pSWMRG->hEventNoWriter;
	aHandles[1]=pSWMRG->hSemNumReaders;
	WaitForMultipleObjects(2,aHandles,TRUE,INFINITE);

// Get the remaining number of readers by releasing the
// semaphore and then restoring the count by immediately
// performing a wait.
	ReleaseSemaphore(pSWMRG->hSemNumReaders,1,&lNumReaders);
	WaitForSingleObject(pSWMRG->hSemNumReaders,INFINITE);

// If there are no remaining readers, 
// set the event to relect this.
	if (lNumReaders==0)
		// If there are no reader threads, 
		// set our event to reflect this.
		SetEvent(pSWMRG->hEventNoReaders);

// Allow other writer/reader threads to use
// the SWMRG synchronization object.
// (it looks like writer is processing thread, but it is not true)
	SetEvent(pSWMRG->hEventNoWriter);
}

DWORD WINAPI WaitToWriteFcn(PSWMRG SObject,PSCOUNTER SCounter)
{
	DWORD EnterCode;
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tSO WaitToWrite: %x\n",SObject);
#endif
	if (WAIT_OBJECT_0==(EnterCode=SWMRGWaitToWrite(SObject,INFINITE)))
		if (SCounter != NULL)
			SCIncFcn(SCounter);
	return EnterCode;
}

void WINAPI WriteDoneFcn(PSWMRG SObject,PSCOUNTER SCounter)
{
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tSO WriteDone: %x\n",SObject);
#endif
	SWMRGDoneWriting(SObject);
	if (SCounter != NULL)
		SCDecFcn(SCounter);
}

DWORD WINAPI WaitToReadFcn(PSWMRG SObject)
{
	DWORD EnterCode;
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tSO WaitToRead: %x\n",SObject);
#endif
	EnterCode=SWMRGWaitToRead(SObject,INFINITE);
	return EnterCode;
}

void WINAPI ReadDoneFcn(PSWMRG SObject)
{
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tSO ReadDone: %x\n",SObject);
#endif
	SWMRGDoneReading(SObject);
}

DWORD WINAPI SCGetNumberFcn(PSCOUNTER SCounter)
{
	DWORD Temp;
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tGetNumber-cs wait\n");
#endif
	EnterCriticalSection(&SCounter->CounterCS);
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tGetNumber-cs enter\n");
#endif
	Temp=SCounter->Number;
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tValue: %d\n",Temp);
	DebugLog(SynchroFile,"\tGetNumber-cs done\n");
#endif
	LeaveCriticalSection(&SCounter->CounterCS);
	return Temp;
}

DWORD WINAPI SCIncFcn(PSCOUNTER SCounter)
{
	DWORD Temp;
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tIncrementValue-cs wait\n");
#endif
	EnterCriticalSection(&SCounter->CounterCS);
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tIncrementValue-cs enter\n");
#endif
	Temp=++SCounter->Number;
	ResetEvent(SCounter->Event);
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tValue: %d\n",Temp);
	DebugLog(SynchroFile,"\tIncrementValue-cs done\n");
#endif
	LeaveCriticalSection(&SCounter->CounterCS);
	return Temp;
}

DWORD WINAPI SCDecFcn(PSCOUNTER SCounter)
{
	DWORD Temp;
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tDecrementValue-cs wait\n");
#endif
	EnterCriticalSection(&SCounter->CounterCS);
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tDecrementValue-cs enter\n");
#endif
	if (!(Temp=--SCounter->Number))
	{
#ifdef DEBUG_SYNCHRO
		DebugLog(SynchroFile,"\tDecrementValue-zero ev set\n");
#endif
		SetEvent(SCounter->Event);
	}
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"\tValue: %d\n",Temp);
	DebugLog(SynchroFile,"\tDecrementValue-cs done\n");
#endif
	LeaveCriticalSection(&SCounter->CounterCS);
	return Temp;
}