private void OnDestroy()
    {
        destroyed = true;
        if (privilegeRequester != null)
        {
            privilegeRequester.OnPrivilegesDone -= handlePrivilegesDone;
        }
        closeClient();

        ssdpRequestThread?.Interrupt();
        ssdpListenThread?.Interrupt();
        connectionThread?.Interrupt();
        receiveThread?.Interrupt();
    }
Exemplo n.º 2
0
        void InternalConnect()
        {
            try
            {
                client.Connect(IP, Port);
                _Connecting = false;

                client.NoDelay     = NoDelay;
                client.SendTimeout = SendTimeout;

                sendThread = new Thread(() => { SendLoop(this); });
                sendThread.IsBackground = true;
                sendThread.Start();

                ReceiveLoop(this);
            }
            catch (SocketException exception)
            {
                Log.WriteNow("Client Recv: failed to connect to ip=" + IP + " port=" + Port + " reason=" + exception);
                OnDisconnect?.Invoke();
            }
            catch (ThreadInterruptedException) { }
            catch (ThreadAbortException) { }
            catch (Exception exception)
            {
                Log.WriteNow("Client Recv Exception: " + exception);
            }

            sendThread?.Interrupt();

            _Connecting = false;

            client?.Close();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Disconnects from the game server.
        /// </summary>
        public void Disconnect()
        {
            if (!isConnecting && !IsConnected)
            {
                Debug.Log("Already disconnected...");
                return;
            }

            Debug.Log("Disconnecting...");

            sslStream?.Close();
            client?.Close();

            // Ensure the receive packets thread exits, and in turn
            // that the send packet thread exits as well
            receivePacketsThread?.Interrupt();

            // We interrupted the receive Thread, so we can't guarantee that
            // connecting was reset. let's do it manually.
            isConnecting = false;

            // No need to continue sending because we're disconnecting.
            // The receive queue though, may still have packets that we
            // want to process.
            sendPacketsQueue.Clear();

            client = null;
        }
Exemplo n.º 4
0
        public void Disconnect()
        {
            // only if started
            if (Connecting || Connected)
            {
                // close client
                client.Close();

                // wait until thread finished. this is the only way to guarantee
                // that we can call Connect() again immediately after Disconnect
                // -> calling .Join would sometimes wait forever, e.g. when
                //    calling Disconnect while trying to connect to a dead end
                receiveThread?.Interrupt();

                // we interrupted the receive Thread, so we can't guarantee that
                // connecting was reset. let's do it manually.
                _Connecting = false;

                // clear send queues. no need to hold on to them.
                // (unlike receiveQueue, which is still needed to process the
                //  latest Disconnected message, etc.)
                sendQueue.Clear();

                // let go of this one completely. the thread ended, no one uses
                // it anymore and this way Connected is false again immediately.
                client = null;
            }
        }
Exemplo n.º 5
0
        private void ReceiveThreadFunction(string ip, int port)
        {
            try
            {
                client.Connect(ip, port);
                _Connecting = false;

                sendThread = new Thread(() => { SendLoop(0, client, sendQueue, sendPending); });
                sendThread.IsBackground = true;
                sendThread.Start();

                ReceiveLoop(0, client, receiveQueue, MaxMessageSize);
            }
            catch (SocketException exception)
            {
                Logger.Log("Client Recv: failed to connect to ip=" + ip + " port=" + port + " reason=" + exception);

                receiveQueue.Enqueue(new Message(0, EventType.Disconnected, null));
            }
            catch (Exception exception)
            {
                Logger.LogError("Client Recv Exception: " + exception);
            }

            sendThread?.Interrupt();

            _Connecting = false;

            client.Close();
        }
Exemplo n.º 6
0
 public void Stop()
 {
     alive = false;
     thread?.Interrupt();
     Join();
     thread = null;
 }
 public void StopBeginReadln()
 {
     _inputReaderThread?.Interrupt();
     _inputReaderThread?.Join();
     _inputReaderThread = null;
     _readingStarted    = false;
 }
Exemplo n.º 8
0
        public void Stop()
        {
            // only if started
            if (!Active)
            {
                return;
            }

            Logger.Log("Server: stopping...");

            // stop listening to connections so that no one can connect while we
            // close the client connections
            // (might be null if we call Stop so quickly after Start that the
            //  thread was interrupted before even creating the listener)
            listener?.Stop();

            // kill listener thread at all costs. only way to guarantee that
            // .Active is immediately false after Stop.
            // -> calling .Join would sometimes wait forever
            listenerThread?.Interrupt();
            listenerThread = null;

            // close all client connections
            foreach (KeyValuePair <int, ClientToken> kvp in clients)
            {
                TcpClient client = kvp.Value.client;
                // close the stream if not closed yet. it may have been closed
                // by a disconnect already, so use try/catch
                try { client.GetStream().Close(); } catch {}
                client.Close();
            }

            // clear clients list
            clients.Clear();
        }
Exemplo n.º 9
0
        // dispose all the state safely
        public void Dispose()
        {
            // close client
            client.Close();

            // wait until thread finished. this is the only way to guarantee
            // that we can call Connect() again immediately after Disconnect
            // -> calling .Join would sometimes wait forever, e.g. when
            //    calling Disconnect while trying to connect to a dead end
            receiveThread?.Interrupt();

            // we interrupted the receive Thread, so we can't guarantee that
            // connecting was reset. let's do it manually.
            Connecting = false;

            // clear send pipe. no need to hold on to elements.
            // (unlike receiveQueue, which is still needed to process the
            //  latest Disconnected message, etc.)
            sendPipe.Clear();

            // IMPORTANT: DO NOT CLEAR RECEIVE PIPE.
            // we still want to process disconnect messages in Tick()!

            // let go of this client completely. the thread ended, no one uses
            // it anymore and this way Connected is false again immediately.
            client = null;
        }
Exemplo n.º 10
0
Arquivo: test.cs Projeto: mono/gert
	static int Main ()
	{
		lock (_lock2) {
			Thread t1;

			lock (_lock1) {
				t1 = new Thread (new ThreadStart(T1));
				t1.Start ();
				Monitor.Wait (_lock1);
			}
			Thread.Sleep (100);
			_actions.Add ("Main: interrupting T1");
			t1.Interrupt ();
		}

#if NET_2_0
		if (_actions.Count != 3) {
#else
		if (_actions.Count != 3) {
#endif
			Console.WriteLine ("#1: " + _actions.Count);
			return 1;
		}

		if ((string) _actions [0] != "T1: started") {
			Console.WriteLine ("#2: " + (string) _actions [0]);
			return 2;
		}

		if ((string) _actions [1] != "T1: trying Lock1") {
			Console.WriteLine ("#3: " + (string) _actions [1]);
			return 3;
		}

		if ((string) _actions [2] != "Main: interrupting T1") {
			Console.WriteLine ("#4: " + (string) _actions [2]);
			return 4;
		}

		return 0;
	}

	static void T1 ()
	{
		_actions.Add ("T1: started");
		lock (_lock1) {
			Monitor.Pulse (_lock1);
		}

		try {
			_actions.Add ("T1: trying Lock1");
			lock (_lock2) {
				_actions.Add ("T1: got Lock1");
			}
		} catch (Exception) {
			_actions.Add ("T1: interrupted");
		}
	}
}
Exemplo n.º 11
0
    private void OnDestroy()
    {
        closeClient();

        connectionThread?.Interrupt();
        ssdpListenThread?.Interrupt();
        ssdpRequestThread?.Interrupt();
    }
Exemplo n.º 12
0
 public void Dispose()
 {
     lock (simulatorLocker)
     {
         simulatorThread?.Interrupt();
         simulatorThread?.Join();
     }
 }
Exemplo n.º 13
0
 public void Dispose()
 {
     _running = false;
     _clientLoop?.Interrupt();
     if (!_clientLoop.Join(1000))
     {
         _clientLoop?.Abort();
     }
 }
Exemplo n.º 14
0
 /// <summary>
 /// Disposes all resources.
 /// </summary>
 public void Dispose()
 {
     if (!disposed)
     {
         disposed = true;
         inputRefresher?.Interrupt();
         inputRefresher?.Join();
     }
 }
Exemplo n.º 15
0
 public void Load(string text)
 {
     lock (playLock)
     {
         if (playing && playThread != null)
         {
             interrupted = true;
             Stop();
             GotKey();
             playThread?.Interrupt();
             playThread?.Join(1000);
             playThread?.Abort();
         }
     }
     backgroundCache = null;
     briefingColor   = 0;
     fullText        = RemoveComments(text).Replace("\r", "");
 }
Exemplo n.º 16
0
        // the thread function
        void ReceiveThreadFunction(string ip, int port)
        {
            // absolutely must wrap with try/catch, otherwise thread
            // exceptions are silent
            try
            {
                // connect (blocking)
                client.Connect(ip, port);
                _Connecting = false;

                // set socket options after the socket was created in Connect()
                // (not after the constructor because we clear the socket there)
                client.NoDelay     = NoDelay;
                client.SendTimeout = SendTimeout;

                // start send thread only after connected
                sendThread = new Thread(() => { SendLoop(0, client, sendQueue, sendPending); });
                sendThread.IsBackground = true;
                sendThread.Start();

                // run the receive loop
                ReceiveLoop(0, client, receiveQueue, MaxMessageSize);
            }
            catch (SocketException exception)
            {
                // this happens if (for example) the ip address is correct
                // but there is no server running on that ip/port
                Logger.Log("Client Recv: failed to connect to ip=" + ip + " port=" + port + " reason=" + exception);

                // add 'Disconnected' event to message queue so that the caller
                // knows that the Connect failed. otherwise they will never know
                receiveQueue.Enqueue(new Message(0, EventType.Disconnected, null));
            }
            catch (Exception exception)
            {
                // something went wrong. probably important.
                Logger.LogError("Client Recv Exception: " + exception);
            }

            // sendthread might be waiting on ManualResetEvent,
            // so let's make sure to end it if the connection
            // closed.
            // otherwise the send thread would only end if it's
            // actually sending data while the connection is
            // closed.
            sendThread?.Interrupt();

            // Connect might have failed. thread might have been closed.
            // let's reset connecting state no matter what.
            _Connecting = false;

            // if we got here then we are done. ReceiveLoop cleans up already,
            // but we may never get there if connect fails. so let's clean up
            // here too.
            client.Close();
        }
Exemplo n.º 17
0
 public void Dispose()
 {
     _stop = true;
     Robustness.Instance.SafeCall(() => { _udpClient?.Dispose(); });
     Robustness.Instance.SafeCall(() =>
     {
         _receiveThread?.Interrupt();
         _receiveThread?.Abort();
     });
 }
Exemplo n.º 18
0
        public void Dispose()
        {
            _messages?.Dispose();
            _executorThread?.Interrupt();

            foreach (var m in _modules.Values)
            {
                m.Dispose();
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Closes the TouchPortal sockets.
        /// And most importantly, interrupts the foreground thread.
        /// </summary>
        /// <param name="exception"></param>
        public void Close(Exception exception)
        {
            _logger.LogInformation($"Closing: {exception}");

            _listenerThread?.Interrupt();
            _streamWriter?.Close();
            _streamReader?.Close();
            _touchPortalSocket?.Close();

            OnDisconnect?.Invoke(exception);
        }
Exemplo n.º 20
0
        private void CancelButton_Click(object sender, EventArgs e)
        {
            backgroundThread?.Interrupt();
            jobThread?.Interrupt();

            backgroundThread?.Join();
            jobThread?.Join();

            backgroundThread = null;
            jobThread        = null;

            WorkerButton.Enabled = true;
        }
Exemplo n.º 21
0
 static void KillTheThread(Thread thread)
 {
     try
     {
         thread?.Interrupt();
         thread?.Abort();
         thread = null;
     }
     catch (Exception e)
     {
         Debug.WriteLine(e);
     }
 }
Exemplo n.º 22
0
        // the thread function
        void ReceiveThreadFunction(string ip, int port)
        {
            // absolutely must wrap with try/catch, otherwise thread
            // exceptions are silent
            try
            {
                // connect (blocking)
                client.Connect(ip, port);
                _Connecting = false;

                // create send queue for this client
                SafeQueue <byte[]> sendQueue = new SafeQueue <byte[]>();
                sendQueues[0] = sendQueue;

                // start send thread only after connected
                sendThread = new Thread(() => { SendLoop(0, client, sendQueue); });
                sendThread.IsBackground = true;
                sendThread.Start();

                // run the receive loop
                ReceiveLoop(0, client, receiveQueue);
            }
            catch (SocketException exception)
            {
                // this happens if (for example) the ip address is correct
                // but there is no server running on that ip/port
                Logger.Log("Client Recv: failed to connect to ip=" + ip + " port=" + port + " reason=" + exception);

                // add 'Disconnected' event to message queue so that the caller
                // knows that the Connect failed. otherwise they will never know
                receiveQueue.Enqueue(new Message(0, EventType.Disconnected, null));
            }
            catch (Exception exception)
            {
                // something went wrong. probably important.
                Logger.LogError("Client Recv Exception: " + exception);
            }

            // try interrupting send thread after receive thread
            // ends, just to be sure
            sendThread?.Interrupt();

            // Connect might have failed. thread might have been closed.
            // let's reset connecting state no matter what.
            _Connecting = false;

            // if we got here then we are done. ReceiveLoop cleans up already,
            // but we may never get there if connect fails. so let's clean up
            // here too.
            client.Close();
        }
        /// <summary>
        /// disposes client and stops threads
        /// </summary>
        public void Dispose()
        {
            Log.Verbose($"Dispose {ToString()}");

            // check hasDisposed first to stop ThreadInterruptedException on lock
            if (hasDisposed)
            {
                return;
            }

            Log.Info($"Connection Close: {ToString()}");


            lock (disposedLock)
            {
                // check hasDisposed again inside lock to make sure no other object has called this
                if (hasDisposed)
                {
                    return;
                }
                hasDisposed = true;

                // stop threads first so they dont try to use disposed objects
                receiveThread.Interrupt();
                sendThread?.Interrupt();

                try
                {
                    // stream
                    stream?.Dispose();
                    stream = null;
                    client.Dispose();
                    client = null;
                }
                catch (Exception e)
                {
                    Log.Exception(e);
                }

                sendPending.Dispose();

                // release all buffers in send queue
                while (sendQueue.TryDequeue(out ArrayBuffer buffer))
                {
                    buffer.Release();
                }

                onDispose.Invoke(this);
            }
        }
Exemplo n.º 24
0
    // Coroutine to attempt fetching pre-registered server address at intervals.
    // Once valid address received, attempt to connect then start receiving stream.
    // The connection logic unfortunately cannot be easily delegated to one thread because
    // UnityWebRequest must be called on the main thread, necessitating a complicated
    // workaround.
    IEnumerator getServerAddress()
    {
        while (!socketConnected)
        {
            MLog("getServerAddress :: Making discovery request");

            discoveryRequest = UnityWebRequest.Get("https://danielchan.io/mldiscovery/get");
            yield return(discoveryRequest.SendWebRequest());

            if (discoveryRequest.isNetworkError || discoveryRequest.isHttpError)
            {
                MLog("getServerAddress :: Error - " + discoveryRequest.error);
            }


            var message = discoveryRequest.downloadHandler.text;
            MLog("getServerAddress :: Received server address - " + message);

            var address = message.Split(':');
            var ip      = address[0];
            var port    = Convert.ToInt32(address[1]);
            if (ip.Equals("") || port < 1)
            {
                continue;
            }

            connectionAttemptFinished     = false;
            connectionThread              = new Thread(() => connectToServerBlocking(ip, port));
            connectionThread.IsBackground = true;
            connectionThread.Start();

            yield return(new WaitUntil(() => connectionAttemptFinished));

            MLog("getServerAddress :: Finished connection attempt");

            yield return(new WaitForSeconds(3));
        }

        receiveThread?.Interrupt();
        writeThread?.Interrupt();

        receiveThread = new Thread(receiveStream);
        receiveThread.IsBackground = true;
        receiveThread.Start();

        writeThread = new Thread(writeStream);
        writeThread.IsBackground = true;
        writeThread.Start();
    }
Exemplo n.º 25
0
        public void Dispose()
        {
            SerialSendThread?.Interrupt();
            SerialSendThread?.Join();

            if (Port != null && Port.IsOpen)
            {
                byte[] bytes = Encoding.ASCII.GetBytes("hvpoe 1 0\r");
                Port.Write(bytes, 0, bytes.Length);
                Thread.Sleep(200);
                bytes = Encoding.ASCII.GetBytes("clra\r\r");
                Port.Write(bytes, 0, bytes.Length);
                Port.Close();
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            // Hack to stop crash.
            // If we do not set ShouldUpdate to false then the component will try and access its disposed self.
            soupGraphicsControl.ShouldUpdate = false;

            if (disposing && (components != null))
            {
                components.Dispose();
            }

            base.Dispose(disposing);

            // Stops any further stat logging.
            _statLoggingThread?.Interrupt();
            _statLoggingThread?.Join();
        }
Exemplo n.º 27
0
 /// <summary>
 /// Stops the emulation of the device
 /// </summary>
 public void Stop()
 {
     if (running)
     {
         running              = false;
         XInput.InputChanged -= XInputInputChanged;
         if (ForceFeedbackSupported)
         {
             controller.FeedbackReceived -= ControllerFeedbackReceived;
             logger.Info($"Force feedback mapping is disconnected on {ToString()}.");
         }
         xOutputInterface?.Unplug(controllerCount);
         logger.Info($"Emulation stopped on {ToString()}.");
         resetId();
         thread?.Interrupt();
     }
 }
Exemplo n.º 28
0
        public void Disconnect()
        {
            if (!Connecting && !Connected)
            {
                return;
            }

            client.Close();

            receiveThread?.Interrupt();

            _Connecting = false;

            sendQueue.Clear();

            client = null;
        }
Exemplo n.º 29
0
        public void Stop()
        {
            serverStopped = true;

            // Interrupt then stop so that Exception is handled correctly
            acceptThread?.Interrupt();
            listener?.Stop();
            acceptThread = null;

            Log.Info("Server stopped, Closing all connections...");
            // make copy so that foreach doesn't break if values are removed
            Connection[] connectionsCopy = connections.Values.ToArray();
            foreach (Connection conn in connectionsCopy)
            {
                conn.Dispose();
            }

            connections.Clear();
        }
Exemplo n.º 30
0
 public void Stop()
 {
     isRunning = false;
     threadRecv?.Interrupt();
     threadRecv = null;
     if (currentSocket != null)
     {
         try
         {
             currentSocket.Shutdown(SocketShutdown.Both);
         }
         catch (Exception e)
         {
             Debuger.LogWarning(e.Message + e.StackTrace);
         }
         currentSocket.Close();
         currentSocket = null;
     }
 }
Exemplo n.º 31
0
        public void Stop()
        {
            if (!Active)
            {
                return;
            }
            Logger.Log("Server: stopping...");
            listener?.Stop();
            listener_thread?.Interrupt();
            listener_thread = null;

            foreach (var kvp in clients)
            {
                var client = kvp.Value.client;
                try { client.GetStream().Close(); } catch {}
                client.Close();
            }
            clients.Clear();
        }
Exemplo n.º 32
0
    static void Main()
    {
        // First, set the name of the current thread so that it's easier
        // to view in the debugger.
        Thread mainThread = Thread.CurrentThread;
        mainThread.Name = "Main Thread";

        // Create an instance of the ThreadedClass.
        ThreadedClass tc1 = new ThreadedClass("Thread1");

        // Set the ThreadedClass's boolean wait forever flag to false.
        tc1.WaitIndefinitely = false;

        // Create the thread giving it the delegate with the
        // method that should be called when the thread starts.
        Console.WriteLine("Main - Creating first worker thread.");
        Thread t1 = new Thread(tc1.ThreadMethod);
        t1.Name = "First Worker Thread";

        // Start the thread
        t1.Start();
        Console.WriteLine ("Main - First worker thread started.");

        // Sleep for a few seconds.
        Console.WriteLine("Main - Sleeping for 5 seconds.");
        Thread.Sleep (5000);

        // Start another thread
        ThreadedClass tc2 = new ThreadedClass("Thread2");
        tc2.WaitIndefinitely = true;
        Console.WriteLine ("Main - Creating second worker thread.");
        Thread t2 = new Thread(tc2.ThreadMethod);
        t2.Name = "Second Worker Thread";
        t2.Start();
        Console.WriteLine ("Main - Second worker thread started.");

        // Sleep for a few seconds.
        Console.WriteLine("Main - Sleeping for 5 seconds.");
        Thread.Sleep(5000);

        // Now wake the second worker thread.
        Console.WriteLine("Main - Interrupting Thread2.");
        t2.Interrupt();

        // Sleep for a few more seconds to give the thread time to finish up.
        Console.WriteLine("Main - Sleeping for 10 seconds.");
        Thread.Sleep(10000);

        Console.Write ("Main - Press <ENTER> to end: ");
        Console.ReadLine();
    }
Exemplo n.º 33
0
		public String testMonitorInterruptDuringWait()
		{
			Thread thread;
			lock (this)
			{
				thread = new Thread(new ThreadStart(threadFunc));
				thread.Start();
				this.seen = false;
				Monitor.Wait(this);
			}
			lock (this.o)
			{
				thread.Interrupt();
				Thread.Sleep(800);
				this.seen = true;
			}
			thread.Join();
			return this.result;
		}
Exemplo n.º 34
0
		public String testMonitorInterruptSleep()
		{
			Thread thread;
			lock (this)
			{
				thread = new Thread(new ThreadStart(threadFunc));
				thread.Start();
				Monitor.Wait(this);
			}
			thread.Interrupt();
			this.seen = true;
			Thread.MemoryBarrier();
			thread.Join();
			return this.result;
		}
Exemplo n.º 35
0
    private static bool TestFairness()
    {
        const int RUN_TIME = 15000;
        const int SETUP_TIME = 20;
        const int READERS = 50;
        const int WRITERS = 10;

        Thread[] rdthrs = new Thread[READERS];
        Thread[] wrthrs = new Thread[WRITERS];

        int[] readersCounters = new int[READERS];
        int[] writersCounters = new int[WRITERS];
        int[] interruptCounters = new int[READERS + WRITERS];
        int sentInterrupts = 0;

        ManualResetEventSlim startEvent = new ManualResetEventSlim(false);
        ReadersWriters_ rwLock = new ReadersWriters_();

        for (int i = 0; i < READERS; i++) {
            int tid = i;
            rdthrs[i] = new Thread(() => {

                // Wait the start for all threads
                startEvent.Wait();

                int endTime = Environment.TickCount + RUN_TIME;
                do {
                    do {
                        try {
                            rwLock.StartRead();
                            break;
                        } catch (ThreadInterruptedException) {
                            interruptCounters[tid]++;
                        }
                    } while (true);
                    Thread.Yield();
                    rwLock.EndRead();
                    if ((++readersCounters[tid] % 1000) == 0) {
                        Console.Write("[#r{0}]", tid);
                    }
                } while (Environment.TickCount < endTime);
                try {
                    Thread.Sleep(0);
                } catch (ThreadInterruptedException) {
                    interruptCounters[tid]++;
                }
            });
            rdthrs[i].Start();
        }

        for (int i = 0; i < WRITERS; i++) {
            int tid = i;
            wrthrs[i] = new Thread(() => {

                // Wait the start for all threads
                startEvent.Wait();

                int endTime = Environment.TickCount + RUN_TIME;
                do {
                    do {
                        try {
                            rwLock.StartWrite();
                            break;
                        } catch (ThreadInterruptedException) {
                            interruptCounters[tid + READERS]++;
                        }
                    } while (true);
                    Thread.Yield();
                    rwLock.EndWrite();
                    if ((++writersCounters[tid] % 1000) == 0) {
                        Console.Write("[#w{0}]", tid);
                    }
                } while (Environment.TickCount < endTime);
                try {
                    Thread.Sleep(0);
                } catch (ThreadInterruptedException) {
                    interruptCounters[tid + READERS]++;
                }
            });
            wrthrs[i].Start();
        }

        // Create the and start the bomber thread...

        Thread bomber = new Thread(() => {
            const int MIN_TIME = 5;
            const int MAX_TIME = 50;

            Random rnd = new Random(Environment.TickCount);

            // Wait the start for all threads
            startEvent.Wait();
            do {
                try {
                    Thread.Sleep(rnd.Next(MIN_TIME, MAX_TIME));
                } catch (ThreadInterruptedException) {
                    break;
                }
                int target = rnd.Next(0, READERS + WRITERS);
                if (target < READERS) {
                    rdthrs[target].Interrupt();
                } else {
                    wrthrs[target - READERS].Interrupt();
                }
                sentInterrupts++;
            } while (true);
        });
        bomber.Start();

        // Sleep for a while and then unblock the test threads.
        Thread.Sleep(SETUP_TIME);
        startEvent.Set();

        Thread.Sleep(RUN_TIME);

        // Interrupt the bomber thread and wait until it has been exited.
        bomber.Interrupt();
        bomber.Join();

        // Wait until all threads have been terminated.
        for (int i = 0; i < READERS + WRITERS; i++) {
         			if (i < READERS)
                rdthrs[i].Join();
            else
                wrthrs[i - READERS].Join();
        }

        // Show results
        Console.WriteLine("\nReader counters:");
        for (int i = 0; i < READERS; i++) {
            if ((i % 5) == 0)
                Console.WriteLine();
            Console.Write("[#r{0}: {1,4}]", i, readersCounters[i]);
        }

        Console.WriteLine("\nWriter counters:");
        for (int i = 0; i < WRITERS; i++) {
            if ((i % 5) == 0)
                Console.WriteLine();
            Console.Write("[#w{0}: {1,4}", i, writersCounters[i]);
        }
        Console.WriteLine("\ninterrupt counters:");
        int sum = 0;
        for (int i = 0; i < READERS + WRITERS; i++) {
            sum += interruptCounters[i];
            if ((i % 5) == 0)
                Console.WriteLine();
            Console.Write("[#{0}: {1,4}]", i, interruptCounters[i]);
        }
        Console.WriteLine("\nsent interrupts: {0}, received: {1}", sentInterrupts, sum);
        return true;
    }
Exemplo n.º 36
0
		public String testMonitorInterruptDuringSleep()
		{
			Thread thread;
			thread = new Thread(new ThreadStart(threadFunc));
			thread.Start();
			while ((thread.ThreadState & ThreadState.WaitSleepJoin) == 0)
				continue;
			thread.Interrupt();
			thread.Join();
			return this.result;
		}