Advertisement
fcamuso

Threads - C

Jun 12th, 2021
1,102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace threads_share_pass_return
  5. {
  6.   class Dati
  7.   {
  8.     static int condivisa_static = 0;
  9.  
  10.     int condivisa = 0;
  11.  
  12.     public void f() {
  13.       Random generatore = new Random();
  14.       Console.WriteLine($"Invocata dal thread {Thread.CurrentThread.Name}");
  15.       condivisa = generatore.Next(100);
  16.       Console.WriteLine($"Ora la variabile condivisa vale: {condivisa}");
  17.     }
  18.  
  19.     public static void f_static()
  20.     {
  21.       Random generatore = new Random();
  22.       Console.WriteLine($"Static. Invocata dal thread {Thread.CurrentThread.Name}");
  23.       condivisa_static = generatore.Next(100);
  24.       Console.WriteLine($"Ora la variabile condivisa statica vale: {condivisa_static}");
  25.     }
  26.   }
  27.  
  28.   class Program
  29.   {
  30.     static void Main(string[] args)
  31.     {
  32.       Dati d = new Dati();
  33.  
  34.       //con variabile di istanza condivisa
  35.       Thread t1 = new Thread(d.f);
  36.       t1.Name = "thread 1";
  37.  
  38.       Thread t2 = new Thread(d.f);
  39.       t2.Name = "thread 2";
  40.  
  41.       t1.Start(); t2.Start();
  42.       t1.Join(); t2.Join();
  43.       Console.WriteLine(new string('-', 80));
  44.      
  45.       //con variabile statica condivisa
  46.       t1 = new Thread(Dati.f_static);
  47.       t1.Name = "thread 1";
  48.  
  49.       t2 = new Thread(Dati.f_static);
  50.       t2.Name = "thread 2";
  51.  
  52.       t1.Start(); t2.Start();
  53.       t1.Join(); t2.Join();
  54.       Console.WriteLine(new string('-', 80));
  55.  
  56.       //con closure su variabile locale
  57.       int condivisa_main = 0;
  58.       Random generatore = new Random();
  59.  
  60.       t1 = new Thread(() =>
  61.       {
  62.         Console.WriteLine($"Main: thread1");
  63.         condivisa_main = generatore.Next(100);
  64.         Console.WriteLine($"Main: ora la variabile locale al main vale: {condivisa_main}");
  65.       });
  66.  
  67.       t1.Name = "thread 1";
  68.  
  69.       t2 = new Thread(() =>
  70.       {
  71.         Console.WriteLine($"Main: thread2");
  72.         condivisa_main = generatore.Next(100);
  73.         Console.WriteLine($"Main: ora la variabile locale al main vale: {condivisa_main}");
  74.       });
  75.  
  76.       t1.Start(); t2.Start();
  77.       t1.Join(); t2.Join();
  78.  
  79.       for (int i = 0; i < 10; i++)
  80.       {
  81.         int temp = i;
  82.         new Thread(() => Console.Write(temp)).Start();
  83.       }
  84.      
  85.  
  86.  
  87.     }
  88.   }
  89. }
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement