Docstoc

Plataforma

Document Sample
Plataforma Powered By Docstoc
					                                  Threads
  A maior parte do suporte visível ao programador é fornecido através
   dos tipos definidos no espaço de nomes System.Threading
  As instâncias de System.Threading.Thread suportam a abstracção
   associada a um fio de execução
  O código associado à thread é especificado através de instâncias de
    delegate void System.ThreadStart()



             …                                                         Ex:
             private void Run() {
                for(int i=0; i<10; ++i) {
                   Console.WriteLine(“Thread Working”); Thread.Sleep(1000);
                }
             }
             …
 Criação     public void StartWork(){
manual de       Thread t = new Thread(new ThreadStart(this.Run)); t.Start();
 thread      }
                             Excerto da classe Thread
Public Properties
    CurrentThread (static)   Gets the currently running thread.

    IsBackground             Gets or sets a value indicating whether or not a thread is a background thread.
    IsThreadPoolThread       Gets a value indicating whether or not a thread belongs to the managed thread pool.
    Name                     Gets or sets the name of the thread.
    Priority                 Gets or sets a value indicating the scheduling priority of a thread.

Public Methods
                             Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of
    Abort                    terminating the thread. Calling this method usually terminates the thread.
    Interrupt                Interrupts a thread that is in the WaitSleepJoin thread state.
    Join                     Overloaded. Blocks the calling thread until a thread terminates.
    Resume                   Resumes a thread that has been suspended.

    Start (static)           Causes the operating system to change the state of the current instance to
                             ThreadState.Running.
    Sleep                    Blocks the current thread for the specified number of milliseconds.
    Suspend                  Either suspends the thread, or if the thread is already suspended, has no effect.

    VolatileRead (static)    Overloaded. Reads the value of a field. The value is the latest written by any processor in a
                             computer, regardless of the number of processors or the state of processor cache.
    VolatileWrite(static)    Overloaded. Writes a value to a field immediately, so that the value is visible to all processors
                             in the computer.
             Suporte Multithreading no CLR (2)
 Suporte explícito (através da FCL)
      Operações atómicas
           System.Threading.Interlocked
      Monitores
           System.Threading.Monitor

 Suporte oferecido pelo runtime (na fase de JIT)
      Escritas e leituras atómicas em dados alinhados e com dimensão menor
       ou igual à do native int
      Escritas e leituras voláteis
      Métodos synchronized
           De instância (utilizando o monitor associado à instância)
           De tipo (utilizando o monitor associado à instância de System.Type que
            representa o tipo)
          Namespace System.Threading (1)

ThreadPool         Provides a pool of threads that can be used to post work items, process
                   asynchronous I/O, wait on behalf of other threads, and process timers.
Mutex              A synchronization primitive than can also be used for interprocess synchronization.

WaitHandle         Encapsulates operating system-specific objects that wait for exclusive access to
                   shared resources.
ManualResetEvent   Notifies one or more waiting threads that an event has occurred. This class cannot be
                   inherited.

AutoResetEvent     Notifies a waiting thread that an event has occurred. This class cannot be inherited.


Monitor            Provides a mechanism that synchronizes access to objects.


ReaderWriterLock   Defines a lock that supports single writers and multiple readers.


Interlocked        Provides atomic operations for variables that are shared by multiple threads
             Namespace System.Threading (2)

              Class                                        Description
Timer                          Provides a mechanism for executing a method at specified intervals.
                               This class cannot be inherited.
Thread                         Creates and controls a thread, sets its priority, and gets its status.
SynchronizationLockException   The exception that is thrown when a method requires the caller to
                               own the lock on a given Monitor, and the method is invoked by a
                               caller that does not own that lock.
ThreadStateException           The exception that is thrown when a Thread is in an invalid
                               ThreadState for the method call.
ThreadInterruptedException     The exception that is thrown when a Thread is interrupted while it is
                               in a waiting state.
ThreadAbortException           The exception that is thrown when a call is made to the Abort
                               method. This class cannot be inherited.
                       System.Threading.Interlocked

        Oferece suporte para operações atómicas
               public class Interlocked
               {
                 // Existem várias sobrecargas de cada operação
                 public static int Increment(ref int);
                 public static int Decrement(ref int);
                 public static int Exchange(ref int, int);
                 public static int CompareExchange(ref int, int, int);
               }


                                                  Ex:
public class IDGenerator {                              int val;
 private static int NextID = 0;                         void EnterSpinLock() {
                                                          while (Interlocked .CompareExchange(ref val, 1, 0) != 0)
    public static int GetID(){                                Thread.Sleep(0);
      // return ++NextID;         // ERRO               }
      return Interlocked.Increment(ref NextID);
    }                                                   void LeaveSpinLock() {
}                                                         Interlocked .Exchange(ref val, 0); // val=0?
                                                        }
                       Estados de uma thread

A thread is created within the common language   Unstarted
runtime.
A thread calls Start                             Running
The thread starts running.                       Running
The thread calls Sleep                           WaitSleepJoin
The thread calls Wait on another object.         WaitSleepJoin
The thread calls Join on another thread.         WaitSleepJoin
Another thread calls Interrupt                   Running
Another thread calls Suspend                     SuspendRequested
The thread responds to a Suspend request.        Suspended
Another thread calls Resume                      Running
Another thread calls Abort                       AbortRequested
The thread responds to a Abort request.          Stopped
A thread is terminated.                          Stopped
                          Mecanismos de Sincronização
                                        ManualResetEvent e AutoResetEvent

Public Constructors


public ManualResetEvent( bool initialState)          Initializes a new instance of the ManualResetEvent class with a Boolean
                                                     value indicating whether to set the initial state to signaled.

Public Methods

 Reset                                        Sets the state of the specified event to nonsignaled.

 Set                                          Sets the state of the specified event to signaled.

 WaitOne (inherited from WaitHandle)          Blocks the current thread until the current WaitHandle receives a signal.


Public Constructors

 public AutoResetEvent( bool initialState)           Initializes a new instance of the AutoResetEvent class

Public Methods

 Set                                          Sets the state of the specified event to signaled.

 WaitOne (inherited from WaitHandle)          Blocks the current thread until the current WaitHandle receives a signal.
                          Mecanismos de Sincronização
                                         Mutex e WaitHandle
Public Constructors

                                            Initializes a new instance of the Mutex class with a Boolean value
   public Mutex(bool, string);             indicating whether the calling thread should have initial ownership of the
                                           mutex, and a string that is the name of the mutex.

Public Methods

   ReleaseMutex                            Releases the Mutex once.

   WaitOne (inherited from WaitHandle)     Overloaded. When overridden in a derived class, blocks the current
                                           thread until the current WaitHandle receives a signal.




Public Methods

   (static) WaitAll                      Overloaded. Waits for all the elements in the specified array to receive a
                                         signal.
   (static) WaitAny                      Overloaded. Waits for any of the elements in the specified array to receive
                                         a signal.
   WaitOne                               Overloaded. When overridden in a derived class, blocks the current thread
                                         until the current WaitHandle receives a signal.
                Demonstração

 Produtores/consumidores
                        Monitores no CLR

 A cada instância de Reference Type é associado, quando
  necessário, um monitor
 O monitor é composto por uma zona de exclusão e uma
  condição que só pode ser acedida pela thread detentora
  da exclusão
 Ao monitor está associado:
      Identificador da thread que detêm a zona de exclusão
      Lista de threads que esperam pelo acesso à zona de exclusão
      Lista de threads que esperam pela condição
                 System.Threading.Monitor
    public class System.Threading.Monitor
    {
      public static void Enter(object);
      public static bool TryEnter(object);   // overloaded
      public static void Exit(object);
      public static void Wait(object);
      public static void Pulse(object);
      public static void PulseAll(object);
    }



 Os métodos Enter e Exit permitem, respectivamente, obter e libertar
  a zona de exclusão
 O método Wait coloca a thread na fila de espera da condição
 Os métodos Pulse e PulseAll colocam uma ou todas as threads da
  fila de espera da condição na fila de espera da exclusão
                                                       C# lock
                       public class IntBox {
                          …
                        public void PutNumber(int number) {
                                 Monitor.Enter(this);
                                 try {
                                    …
                                 }
                                 finally {
                                     Monitor.Exit(this);
                                 }
                        }
                        …
                       }
                                                                          public class IntBox {
                                                                             …
public class IntBox {                                                      public void PutNumber(int number)
                                                                           {
    [MethodImpl (MethodImplOptions. Synchronized)]                              lock(this) { … }
                                                                           }
    public void PutNumber(int number){                                       …
    }                                                                     }
    …
}
       No caso de método estático, o objecto sobre o qual se faz lock é
       O retornado por typeof(IntBox)
                under the hood: SyncBlocks
                                          CLR Data
   “In place”       Managed               Structures
                     Heap
                                        IntBox Type Desc
    reference       sync# (0)
                    sync# (-1)
                      htype
                                          Type Info
                                         Method Table
                    Campos de
                     instância
                                        SyncBlock Cache

                                         SyncBlock #0
class IntBox {                           SyncBlock #1
  ...                                          ...
  public void PutNumber(int number)      SyncBlock #n
  {
    Monitor.Enter(this); // na 1ª vez
    ...
  }
}
                     Monitores e Value Types
 O monitor só pode ser associado a instâncias de Reference Types
 Existe boxing na tentativa de associação de instâncias de Value Types
  a monitores
      Neste caso não existe sincronização entre threads



                                  Ex 1:                                 Ex 2:
  public class SomeType                     public class SomeType
  {                                         {
     private bool flag = false;                private bool flag = false;
     public void DoSomething()                 public void DoSomething()
     {                                         {
        object o = flag;                          Monitor.Enter(flag);
        Monitor.Enter(o);                         …
        …
                                                  Monitor.Exit(flag);
        Monitor.Exit(o);
                                               }
     }
                                            }
  }
Thread Pool
                                             ThreadPool
                                                                                       Existe apenas uma
                                                                                       pool por processo
Public Methods

GetAvailableThreads (static)        Retrieves the difference between the maximum number of
                                    thread pool threads, returned by GetMaxThreads, and the
                                    number currently active.
GetMaxThreads (static)              Retrieves the number of requests to the thread pool that can
                                    be active concurrently. All requests above that number
                                    remain queued until thread pool threads become available.
QueueUserWorkItem (static)          Overloaded. Queues a method for execution. The method
                                    executes when a thread pool thread becomes available.



  Formas indirectas
   de criar fios de
     execução                  •   Calling   a method   asynchronously
                               •   Calling   a method   at a timed interval
                               •   Calling   a method   when a single kernel object is signaled
                               •   Calling   a method   when an asynchronous I/O request completes
              Formas indirectas de criar fios de execução
                                     ThreadPool.QueueUserWorkItem

using System;                public delegate void WaitCallback (object state);
using System.Threading;      public static bool QueueUserWorkItem (WaitCallback callBack, object state)
class App {
   static void Main() {
      Console.WriteLine("Main thread: Queuing an aynchronous        operation.");

        ThreadPool.QueueUserWorkItem(new WaitCallback(MyAsyncOperation));
        Console.WriteLine("Main thread: Performing other operations.");
        // ...
        Console.WriteLine("Main thread: Pausing to simulate doing other operations.");
        Console.ReadLine();
    }

    // The callback method's signature MUST match that of a
    // System.Threading.WaitCallback delegate (it takes an
    // Object parameter and returns void)

    static void MyAsyncOperation(Object state) {
       Console.WriteLine("ThreadPool thread: Performing aynchronous operation.");
       // ...
       Thread.Sleep(5000);    // Sleep for 5 seconds to simulate doing work

        // Returning from this method causes the thread to
        // suspend itself waiting for another task
    }
}
             Formas indirectas de criar fios de execução
                               Timers
using System;           public Timer(TimerCallback callback,object state, int dueTime, int period)
using System.Threading;

class App {
   static void Main() {
      Console.WriteLine("Checking for status updates every 2 seconds.");
      Console.WriteLine("   (Hit Enter to terminate the sample)");

        Timer timer = new Timer(new TimerCallback(CheckStatus),null,0, 2000);

        Console.ReadLine();
    }

    // The callback method's signature MUST match that of a
    // System.Threading.TimerCallback delegate (it takes an
    // Object parameter and returns void)
    static void CheckStatus(Object state) {
       Console.WriteLine("Checking Status.");
       // ...
    }                   If the pool is full (all its threads are being used), the request waits in the queue
}                                 and the timer is no longer accurate.
                                If several timers are created, the thread pool is busy waiting for them to expire.
           Formas indirectas de criar fios de execução
                         ThreadPool.RegisterWaitForSingleObject
class App {
   static void Main() {
      AutoResetEvent are = new AutoResetEvent(false);

        RegisteredWaitHandle rwh = ThreadPool.RegisterWaitForSingleObject(
            are, new WaitOrTimerCallback(EventSignalled), null, -1, false);

        for (Int32 x = 0 ; x < 5; x++) {
           Thread.Sleep(5000);             public static RegisterWaitHandle
           are.Set();                      RegisterWaitForSingleObject( WaitHandle h,
        }                                                               WaitOrTimerCallback callback,
                                                                        Object state,
        rwh.Unregister(null);                                           UInt32 milliseconds,
        Console.ReadLine();                                             Boolean executeOnlyOnce);
    }

    // The callback method's signature MUST match that of a
    // System.Threading.WaitOrTimerCallback delegate (it takes an
    // Object parameter and a Boolean and returns void)
    static void EventSignalled(Object state, Boolean timedOut) {
       if (timedOut) {
          Console.WriteLine("Timed-out while waiting for the AutoResetEvent.");
       } else {
          Console.WriteLine("The AutoResetEvent became signalled.");
       }
       // ...
    }
}
               Delegates – chamada assíncrona
                         de callbacks
                                                                  Um tipodelegate é derivado de
                                                                  MultiCastDelegate. Os métodos
                                                                  BeginInvoke e EndInvoke são usados
                                                                  nas chamadas assíncronas




A interface IAsyncResult serve para
obter informação sobre a chamada
assíncrona
                     AsyncState                                 Gets a user-defined object that qualifies or
                     Supported by the .NET Compact Framework.   contains information about an asynchronous
                                                                operation.
                     AsyncWaitHandle                            Gets a WaitHandle that is used to wait for an
                     Supported by the .NET Compact Framework.   asynchronous operation to complete.
                     CompletedSynchronously                     Gets an indication of whether the asynchronous
                     Supported by the .NET Compact Framework.   operation completed synchronously.
                     IsCompleted                                Gets an indication whether the asynchronous
                     Supported by the .NET Compact Framework.   operation has completed.
       Delegates – exemplo de chamada
           assíncrona de callbacks
public void DoWork() {
         Console.WriteLine("Trabalhador: Iniciei o trabalho");
         if(Started!=null) Started();


        if(Completed!=null) {
          foreach(WorkCompleted wc in Completed.GetInvocationList())
                 FireAndNotifyMeCompleted(wc);
        }
}

private void FireAndNotifyMeCompleted(WorkCompleted wc) {
         wc.BeginInvoke(new AsyncCallback(this.CollectGrade), wc);
}

private void CollectGrade(IAsyncResult res) {
    WorkCompleted wc = (WorkCompleted) res.AsyncState;
    int grade = wc.EndInvoke(res);
    Console.WriteLine("Classificação do trabalhador=" + grade);
}
Invocação Assíncrona de Delegates

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:24
posted:3/30/2011
language:Portuguese
pages:23