Salome HOME
PR: mergefrom_BR_CCRT_11Nov04
[modules/yacs.git] / src / SALOMELocalTrace / LocalTraceBufferPool.cxx
1 //  Copyright (C) 2004  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
3 // 
4 //  This library is free software; you can redistribute it and/or 
5 //  modify it under the terms of the GNU Lesser General Public 
6 //  License as published by the Free Software Foundation; either 
7 //  version 2.1 of the License. 
8 // 
9 //  This library is distributed in the hope that it will be useful, 
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 //  Lesser General Public License for more details. 
13 // 
14 //  You should have received a copy of the GNU Lesser General Public 
15 //  License along with this library; if not, write to the Free Software 
16 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
17 // 
18 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
19 //
20 //  Author : Paul RASCLE (EDF)
21 //  Module : KERNEL
22 //  $Header$
23 //
24 // Cf. C++ Users Journal, June 2004, Tracing Application Execution, Tomer Abramson
25 //
26
27 #include <iostream>
28 #include <limits.h>
29
30 #include "LocalTraceBufferPool.hxx"
31 #include "utilities.h"
32
33 using namespace std;
34
35 // In case of truncated message, end of trace contains "...\n\0"
36 #define TRUNCATED_MESSAGE "...\n"
37 #define MAXMESS_LENGTH MAX_TRACE_LENGTH-5
38
39 LocalTraceBufferPool* LocalTraceBufferPool::_singleton = 0;
40 pthread_mutex_t LocalTraceBufferPool::_singletonMutex;
41
42 // ============================================================================
43 /*!
44  *  guarantees a unique object instance of the class (singleton thread safe)
45  */
46 // ============================================================================
47
48 LocalTraceBufferPool* LocalTraceBufferPool::instance()
49 {
50   if (_singleton == 0) // no need of lock when singleton already exists
51     {
52       int ret;
53       ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
54       if (_singleton == 0)                     // another thread may have got
55         {                                      // the lock after the first test
56           _singleton = new LocalTraceBufferPool(); 
57         }
58       ret = pthread_mutex_unlock(&_singletonMutex); // release lock
59     }
60   return _singleton;
61 }
62
63 // ============================================================================
64 /*!
65  *  Called by trace producers within their threads. The trace message is copied
66  *  in specific buffer from a circular pool of buffers.
67  *  Waits until there is a free buffer in the pool, gets the first available
68  *  buffer, fills it with the message.
69  *  Messages are printed in a separate thread (see retrieve method)
70  */
71 // ============================================================================
72
73 int LocalTraceBufferPool::insert(int traceType, const char* msg)
74 {
75
76   // get immediately a message number to control sequence (mutex protected)
77
78   unsigned long myMessageNumber = lockedIncrement(_position);
79
80   // wait until there is a free buffer in the pool
81
82   int ret = sem_wait(&_freeBufferSemaphore);
83
84   // get the next free buffer available (mutex protected) 
85
86   unsigned long myInsertPos = lockedIncrement(_insertPos);
87
88   // fill the buffer with message, thread id and type (normal or abort)
89
90   strncpy(_myBuffer[myInsertPos%TRACE_BUFFER_SIZE].trace,
91           msg,
92           MAXMESS_LENGTH); // last chars always "...\n\0" if msg too long
93   _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].threadId =pthread_self();//thread id
94   _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].traceType = traceType;
95   _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].position = myMessageNumber;
96
97
98   // increment the full buffer semaphore
99   // (if previously 0, awake thread in charge of trace)
100
101   ret = sem_post(&_fullBufferSemaphore);
102
103   // returns the number of free buffers
104
105   sem_getvalue(&_freeBufferSemaphore, &ret);
106   return ret;  
107 }
108
109 // ============================================================================
110 /*!
111  *  Called by the thread in charge of printing trace messages.
112  *  Waits until there is a buffer with a message to print.
113  *  Gets the first buffer to print, copies it int the provided buffer
114  */
115 // ============================================================================
116
117 int LocalTraceBufferPool::retrieve(LocalTrace_TraceInfo& aTrace)
118 {
119
120   // wait until there is a buffer in the pool, with a message to print
121
122   int ret = sem_wait(&_fullBufferSemaphore);
123
124   // get the next buffer to print
125
126   unsigned long myRetrievePos = lockedIncrement(_retrievePos);
127
128   // copy the buffer from the pool to the provided buffer
129
130   memcpy((void*)&aTrace,
131          (void*)&_myBuffer[myRetrievePos%TRACE_BUFFER_SIZE],
132          sizeof(aTrace));
133
134   // increment the free buffer semaphore
135   // (if previously 0, awake one of the threads waiting to put a trace, if any)
136   // there is no way to preserve the order of waiting threads if several
137   // threads are waiting to put a trace: the waken up thread is not
138   // necessarily the first thread to wait.
139
140   ret = sem_post(&_freeBufferSemaphore);
141
142   // returns the number of full buffers
143
144   sem_getvalue(&_fullBufferSemaphore, &ret);
145   return ret;
146 }
147
148 // ============================================================================
149 /*!
150  *  Gives the number of buffers to print.
151  *  Usage : when the thread in charge of messages print id to be stopped,
152  *  check if there is still something to print, before stop.
153  *  There is no need of mutex here, provided there is only one thread to
154  *  retrieve and print the buffers.
155  */
156 // ============================================================================
157
158 unsigned long LocalTraceBufferPool::toCollect()
159 {
160   return _insertPos - _retrievePos;
161 }
162
163 // ============================================================================
164 /*!
165  * Constructor : initialize pool of buffers, semaphores and mutex.
166  */
167 // ============================================================================
168
169 LocalTraceBufferPool::LocalTraceBufferPool()
170 {
171   //cout << "LocalTraceBufferPool::LocalTraceBufferPool()" << endl;
172
173   _insertPos   = ULONG_MAX;  // first increment will give 0
174   _retrievePos = ULONG_MAX;
175   _position=0;               // first message will have number = 1
176
177   memset(_myBuffer, 0, sizeof(_myBuffer)); // to guarantee end of strings = 0
178   for (int i=0; i<TRACE_BUFFER_SIZE; i++)
179     strcpy(&(_myBuffer[i].trace[MAXMESS_LENGTH]),TRUNCATED_MESSAGE);
180   int ret;
181   ret=sem_init(&_freeBufferSemaphore, 0, TRACE_BUFFER_SIZE); // all buffer free
182   if (ret!=0) IMMEDIATE_ABORT(ret);
183   ret=sem_init(&_fullBufferSemaphore, 0, 0);                 // 0 buffer full
184   if (ret!=0) IMMEDIATE_ABORT(ret);
185   ret=pthread_mutex_init(&_incrementMutex,NULL); // default = fast mutex
186   if (ret!=0) IMMEDIATE_ABORT(ret);
187 }
188
189 // ============================================================================
190 /*!
191  * Destructor : release memory associated with semaphores and mutex
192  */
193 // ============================================================================
194
195 LocalTraceBufferPool::~LocalTraceBufferPool()
196 {
197   int ret;
198   ret=sem_destroy(&_freeBufferSemaphore);
199   ret=sem_destroy(&_fullBufferSemaphore);
200   ret=pthread_mutex_destroy(&_incrementMutex);
201 }
202
203 // ============================================================================
204 /*!
205  * pool counters are incremented under a mutex protection
206  */
207 // ============================================================================
208
209 unsigned long LocalTraceBufferPool::lockedIncrement(unsigned long& pos)
210 {
211   int ret;
212   ret = pthread_mutex_lock(&_incrementMutex);   // lock access to counters
213   pos++;
214   ret = pthread_mutex_unlock(&_incrementMutex); // release lock
215   return pos;
216 }
217