@@ -7,6 +7,10 @@ namespace Sapling;
7
7
8
8
internal class Program
9
9
{
10
+ private static readonly ConcurrentQueue < string > commandQueue = new ( ) ;
11
+ private static readonly ManualResetEventSlim commandAvailable = new ( false ) ;
12
+ private static bool hasQuit = false ;
13
+
10
14
private static void Main ( string [ ] args )
11
15
{
12
16
if ( args . Length > 0 && args [ 0 ] == "--version" )
@@ -83,42 +87,14 @@ private static void Main(string[] args)
83
87
{
84
88
UciEngine engine = new ( logWriter ) ;
85
89
86
- var commandQueue = new ConcurrentQueue < string > ( ) ;
87
-
88
- var hasQuit = false ;
90
+ // Start the command reading task
89
91
_ = Task . Run ( ( ) =>
90
92
{
91
- while ( true )
92
- {
93
- var command = Console . ReadLine ( ) ;
94
- if ( string . IsNullOrEmpty ( command ) )
95
- {
96
- continue ;
97
- }
98
-
99
- if ( command . Contains ( "quit" ) )
100
- {
101
- hasQuit = true ;
102
- break ;
103
- }
104
-
105
- if ( command . Contains ( "stop" ) )
106
- {
107
- engine . ReceiveCommand ( command ) ;
108
- continue ;
109
- }
110
-
111
- commandQueue . Enqueue ( command ) ;
112
- }
93
+ ReadCommands ( engine ) ;
113
94
} ) ;
114
95
115
- while ( ! hasQuit )
116
- {
117
- if ( commandQueue . TryDequeue ( out var command ) )
118
- {
119
- engine . ReceiveCommand ( command ) ;
120
- }
121
- }
96
+ // Process commands in the main loop
97
+ ProcessCommands ( engine ) ;
122
98
}
123
99
catch ( Exception ex )
124
100
{
@@ -132,4 +108,48 @@ private static void Main(string[] args)
132
108
logWriter . Flush ( ) ;
133
109
}
134
110
}
111
+
112
+ private static void ReadCommands ( UciEngine engine )
113
+ {
114
+ while ( true )
115
+ {
116
+ var command = Console . ReadLine ( ) ;
117
+ if ( string . IsNullOrEmpty ( command ) )
118
+ {
119
+ continue ; // Skip empty commands
120
+ }
121
+
122
+ if ( command . Contains ( "quit" , StringComparison . OrdinalIgnoreCase ) )
123
+ {
124
+ hasQuit = true ;
125
+ commandQueue . Enqueue ( command ) ;
126
+ commandAvailable . Set ( ) ; // Signal that a command is available
127
+ break ;
128
+ }
129
+
130
+ if ( command . Contains ( "stop" , StringComparison . OrdinalIgnoreCase ) )
131
+ {
132
+ // Process the stop command immediately
133
+ engine . ReceiveCommand ( command ) ;
134
+ continue ;
135
+ }
136
+
137
+ commandQueue . Enqueue ( command ) ;
138
+ commandAvailable . Set ( ) ; // Signal that a command is available
139
+ }
140
+ }
141
+
142
+ private static void ProcessCommands ( UciEngine engine )
143
+ {
144
+ while ( ! hasQuit )
145
+ {
146
+ commandAvailable . Wait ( ) ; // Wait until a command is available
147
+ commandAvailable . Reset ( ) ; // Reset the event for the next wait
148
+
149
+ while ( commandQueue . TryDequeue ( out var command ) )
150
+ {
151
+ engine . ReceiveCommand ( command ) ;
152
+ }
153
+ }
154
+ }
135
155
}
0 commit comments