aboutsummaryrefslogtreecommitdiff
path: root/ChocolArm64/AThread.cs
blob: 5c03228943cbb2fd656000d16909577315a08635 (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
using ChocolArm64.Memory;
using ChocolArm64.State;
using System;
using System.Threading;

namespace ChocolArm64
{
    public class AThread
    {
        public AThreadState ThreadState { get; private set; }
        public AMemory      Memory      { get; private set; }

        public long EntryPoint { get; private set; }

        private ATranslator Translator;

        private ThreadPriority Priority;

        private Thread Work;

        public event EventHandler WorkFinished;

        public int ThreadId => ThreadState.ThreadId;

        public bool IsAlive => Work.IsAlive;

        private bool IsExecuting;

        private object ExecuteLock;

        public AThread(AMemory Memory, ThreadPriority Priority, long EntryPoint)
        {
            this.Memory     = Memory;
            this.Priority   = Priority;
            this.EntryPoint = EntryPoint;

            ThreadState = new AThreadState();
            Translator  = new ATranslator(this);
            ExecuteLock = new object();
        }

        public void StopExecution() => Translator.StopExecution();

        public bool Execute()
        {
            lock (ExecuteLock)
            {
                if (IsExecuting)
                {
                    return false;
                }

                IsExecuting = true;
            }

            Work = new Thread(delegate()
            {
                Translator.ExecuteSubroutine(EntryPoint);

                Memory.RemoveMonitor(ThreadId);

                WorkFinished?.Invoke(this, EventArgs.Empty);
            });

            Work.Priority = Priority;

            Work.Start();

            return true;
        }
    }
}