Skip to content

Commit cd9bf4c

Browse files
Making WorkerThread static
- Making WorkerThread instance static - Adding PythonInitialize.AddPythonPaths(), useful to add paths to python after initialization
1 parent 63847a3 commit cd9bf4c

File tree

7 files changed

+45
-11
lines changed

7 files changed

+45
-11
lines changed

Common/Python/PythonInitializer.cs

+17
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
*
1515
*/
1616

17+
using System.Collections.Generic;
18+
using System.Linq;
1719
using Python.Runtime;
1820
using QuantConnect.Logging;
1921

@@ -44,5 +46,20 @@ public static void Initialize()
4446
Log.Trace("PythonInitializer.Initialize(): ended");
4547
}
4648
}
49+
50+
/// <summary>
51+
/// Adds directories to the python path at runtime
52+
/// </summary>
53+
public static void AddPythonPaths(IEnumerable<string> paths)
54+
{
55+
if (_isBeginAllowThreadsCalled)
56+
{
57+
using (Py.GIL())
58+
{
59+
var code = string.Join(";", paths.Select(s => $"sys.path.append('{s}')"));
60+
PythonEngine.Exec($"import sys;{code}");
61+
}
62+
}
63+
}
4764
}
4865
}

Common/Util/WorkerThread.cs

+6-1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ public class WorkerThread : IDisposable
3131
private readonly CancellationTokenSource _threadCancellationTokenSource;
3232
private readonly Thread _workerThread;
3333

34+
/// <summary>
35+
/// The worker thread instance
36+
/// </summary>
37+
public static WorkerThread Instance = new WorkerThread();
38+
3439
/// <summary>
3540
/// Will be set when the worker thread finishes a work item
3641
/// </summary>
@@ -40,7 +45,7 @@ public class WorkerThread : IDisposable
4045
/// Creates a new instance, which internally launches a new worker thread
4146
/// </summary>
4247
/// <remarks><see cref="Dispose"/></remarks>
43-
public WorkerThread()
48+
protected WorkerThread()
4449
{
4550
_threadCancellationTokenSource = new CancellationTokenSource();
4651
FinishedWorkItem = new AutoResetEvent(false);

Engine/Engine.cs

+3-5
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,10 @@ public Engine(LeanEngineSystemHandlers systemHandlers, LeanEngineAlgorithmHandle
7979
/// Runs a single backtest/live job from the job queue
8080
/// </summary>
8181
/// <param name="job">The algorithm job to be processed</param>
82-
/// <param name="manager"></param>
82+
/// <param name="manager">The algorithm manager instance</param>
8383
/// <param name="assemblyPath">The path to the algorithm's assembly</param>
84-
public void Run(AlgorithmNodePacket job, AlgorithmManager manager, string assemblyPath)
84+
/// <param name="workerThread">The worker thread instance</param>
85+
public void Run(AlgorithmNodePacket job, AlgorithmManager manager, string assemblyPath, WorkerThread workerThread)
8586
{
8687
var marketHoursDatabaseTask = Task.Run(() => StaticInitializations());
8788

@@ -96,7 +97,6 @@ public void Run(AlgorithmNodePacket job, AlgorithmManager manager, string assemb
9697
Thread threadResults = null;
9798
Thread threadRealTime = null;
9899
Thread threadAlphas = null;
99-
WorkerThread workerThread = null;
100100

101101
//-> Initialize messaging system
102102
SystemHandlers.Notify.SetAuthentication(job);
@@ -116,8 +116,6 @@ public void Run(AlgorithmNodePacket job, AlgorithmManager manager, string assemb
116116
// since the algorithm constructor will use it
117117
var marketHoursDatabase = marketHoursDatabaseTask.Result;
118118

119-
// start worker thread
120-
workerThread = new WorkerThread();
121119
AlgorithmHandlers.Setup.WorkerThread = workerThread;
122120

123121
// Save algorithm to cache, load algorithm instance:

Launcher/Program.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ static void Main(string[] args)
127127
leanEngineSystemHandlers.LeanManager.Initialize(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, job, algorithmManager);
128128

129129
var engine = new Engine.Engine(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, liveMode);
130-
engine.Run(job, algorithmManager, assemblyPath);
130+
engine.Run(job, algorithmManager, assemblyPath, WorkerThread.Instance);
131131
}
132132
finally
133133
{

Tests/AlgorithmFactory/LoaderTests.cs

+6-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public class LoaderTests
3030
[SetUp]
3131
public void SetUp()
3232
{
33-
_workerThread = new WorkerThread();
33+
_workerThread = new TestWorkerThread();
3434
}
3535

3636
[TearDown]
@@ -108,5 +108,10 @@ public void LoadsSepereateAlgorithm_UsingSingleOrAlgorithmTypeName_ExtensionMeth
108108
Assert.IsTrue(two);
109109
Assert.AreNotEqual(algorithm1.ToString(), algorithm2.ToString());
110110
}
111+
112+
private class TestWorkerThread : WorkerThread
113+
{
114+
115+
}
111116
}
112117
}

Tests/AlgorithmRunner.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ public static AlgorithmManager RunLocalBacktest(
120120

121121
systemHandlers.LeanManager.Initialize(systemHandlers, algorithmHandlers, job, algorithmManager);
122122

123-
engine.Run(job, algorithmManager, algorithmPath);
123+
engine.Run(job, algorithmManager, algorithmPath, new TestWorkerThread());
124124
ordersLogFile = ((RegressionResultHandler)algorithmHandlers.Results).LogFilePath;
125125
}
126126
catch (Exception e)
@@ -237,5 +237,9 @@ public override IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> reques
237237
return base.GetHistory(requests, sliceTimeZone);
238238
}
239239
}
240+
241+
class TestWorkerThread : WorkerThread
242+
{
243+
}
240244
}
241245
}

Tests/Common/IsolatorTests.cs

+7-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public class IsolatorTests
2727
[Test]
2828
public void WorksCorrectlyUsingWorker()
2929
{
30-
using (var worker = new WorkerThread())
30+
using (var worker = new TestWorkerThread())
3131
{
3232
var isolator = new Isolator();
3333
var executed = false;
@@ -51,7 +51,7 @@ public void WorksCorrectlyUsingWorker()
5151
[TestCase(Language.CSharp, false)]
5252
public void TimeOutWorkCorrectly(Language language, bool useWorker)
5353
{
54-
var worker = useWorker ? new WorkerThread() : null;
54+
var worker = useWorker ? new TestWorkerThread() : null;
5555
using (worker)
5656
{
5757
var isolator = new Isolator();
@@ -92,5 +92,10 @@ public void TimeOutWorkCorrectly(Language language, bool useWorker)
9292
}
9393
}
9494
}
95+
96+
private class TestWorkerThread : WorkerThread
97+
{
98+
99+
}
95100
}
96101
}

0 commit comments

Comments
 (0)