Upstream tarball 9882
[amule.git] / src / StateMachine.cpp
blobdac45016c2439d62958a76c5fabb2b3f077a5a43
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2005-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2004-2008 Marcelo Roberto Jimenez ( phoenix@amule.org )
6 //
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
9 // respective authors.
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
20 //
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include "StateMachine.h"
28 #include <common/StringFunctions.h>
30 CStateMachine::CStateMachine(
31 const wxString &name,
32 const unsigned int maxStates,
33 const t_sm_state initialState )
35 m_stateMutex(wxMUTEX_RECURSIVE),
36 m_queueMutex(wxMUTEX_RECURSIVE),
37 m_name(name),
38 m_maxStates(maxStates),
39 m_initialState(initialState)
41 m_state = initialState;
42 m_clockCounter = 0;
43 m_clocksInCurrentState = 0;
46 CStateMachine::~CStateMachine()
50 void CStateMachine::Clock()
52 t_sm_state old_state;
53 t_sm_event event;
54 bool state_entry;
56 old_state = m_state;
58 /* Process state change acording to event */
59 if (!m_queue.empty()) {
60 event = m_queue.front();
61 m_queue.pop();
62 } else {
63 event = 0;
66 /* State changes can only happen here */
67 wxMutexLocker lock(m_stateMutex);
68 m_state = next_state( event );
70 //#if 0
71 /* Debug */
72 ++m_clockCounter;
73 state_entry = ( m_state != old_state ) || ( m_clockCounter == 1 );
74 if( state_entry )
76 m_clocksInCurrentState = 0;
77 printf( "%s(%04d): %d -> %d\n",
78 (const char *)unicode2char(m_name),
79 m_clockCounter, old_state, m_state);
81 ++m_clocksInCurrentState;
82 //#endif
84 /* Process new state entry */
85 if( m_state < m_maxStates )
87 /* It should be ok to call Clock() recursively inside this
88 * procedure because state change has already happened. Also
89 * the m_state mutex is recursive. */
90 process_state(m_state, state_entry);
94 /* In multithreaded implementations, this must be locked */
95 void CStateMachine::Schedule(t_sm_event event)
97 wxMutexLocker lock(m_queueMutex);
98 m_queue.push(event);
101 void CStateMachine::flush_queue()
103 while (!m_queue.empty()) {
104 m_queue.pop();
107 // File_checked_for_headers