我正在研究一個與執行緒相關的復雜專案。這是對我的問題的最簡單解釋。下面是代碼,這里有 3 個函式,不包括 main 函式。所有功能都在多執行緒中運行。所有函式都有一個while回圈。我只想分別從“func1”和“func2”中獲取變數“i”和“k”并在“func3”中使用它。這些變數在 while 回圈中更新。這是代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Threading
{
class Program
{
public static void func1() //How can I get the variable "i" from the while loop. Note: This function is running in thread.
{
int i = 1;
while (true)
{
Console.WriteLine("Func1: " i);
i ;
}
}
public static void func2() //How can I get the variable "k" from the while loop. Note: This function is running in thread.
{
int k = 1;
while (true)
{
Console.WriteLine("Func2: " k);
k ;
}
}
public static void func3() //After getting variables from func1 and func2 I want them to use in function 3.
{
while (true)
{
int sum = i k;
Console.WriteLine("the sum is" sum);
}
}
public static void Main(string[] args)
{
Thread t1 = new Thread(func1);
Thread t2 = new Thread(func2);
Thread t3 = new Thread(func3);
t1.Start();
t2.Start();
t3.Start();
}
}
}
uj5u.com熱心網友回復:
您可能需要將iandk從區域變數提升到Program類的私有欄位。由于這兩個欄位將被多個執行緒訪問而無需同步,因此您還應該將它們宣告為volatile:
private static volatile int i = 1;
private static volatile int k = 1;
public static void func1()
{
while (true)
{
Console.WriteLine("Func1: " i);
i ;
}
}
public static void func2()
{
while (true)
{
Console.WriteLine("Func2: " k);
k ;
}
}
public static void func3()
{
while (true)
{
int sum = i k;
Console.WriteLine("the sum is" sum);
}
}
訪問模式volatile雖然使用有點浪費。Thefunc1是唯一改變 的方法i,因此在該方法中使用 volatile 語意讀取它是純粹的開銷。您可以改用Volatile.ReadandVolatile.Write方法進行更精細的控制:
private static int i = 1;
private static int k = 1;
public static void func1()
{
while (true)
{
Console.WriteLine("Func1: " i);
Volatile.Write(ref i, i 1);
}
}
public static void func2()
{
while (true)
{
Console.WriteLine("Func2: " k);
Volatile.Write(ref k, k 1);
}
}
public static void func3()
{
while (true)
{
int sum = Volatile.Read(ref i) Volatile.Read(ref k);
Console.WriteLine("the sum is" sum);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452674.html
上一篇:如何檢查影像檔案是否有效?
