gpt4 book ai didi

c# - 一个由不同线程分别创建的对象仍然是共享的

转载 作者:太空宇宙 更新时间:2023-11-03 19:40:56 25 4
gpt4 key购买 nike

我有一个程序,我想在其中模拟一个队列。为了加快速度(很多不同的参数)我认为我可以使用并行循环,但是队列对象(或至少该对象中的对象)仍然共享,而它们都是在 MGcC 函数或队列中创建的目的。有什么我忘记了并行功能吗?

产生问题的对象是 queue.MyHeap。

(此外,如果需要更多信息,请询问,因为我已经遗漏了很多信息以使其更具可读性,正如您在队列对象中看到的那样)。

Parallel.ForEach(a, (numbers) =>
{
MGcC(a);
});

static public Tuple<Customer[,], List<Interval>[]> MGcC(int a)
{
Queue queue = new Queue(a);
return queue.Simulate(writeFile);
}

public class Queue
{
Func<object, double> arrivalFunction;
Func<object, double> servingFunction;
double lambda;
double v;
object serviceObject;
int minServers;
bool decision;

int idleServers;
int activeServers;
int amountInOrbit;
protected minHeap myHeap;

public Queue(double lambda, double v, object serviceObject, int servers, Func<object, double> arrivalFunction, Func<object, double> servingFunction, bool decision = false)
{
this.arrivalFunction = arrivalFunction;
this.servingFunction = servingFunction;
this.lambda = lambda;
this.v = v;
this.serviceObject = serviceObject;
this.minServers = servers;
this.decision = decision;

idleServers = servers;
activeServers = 0;
amountInOrbit = 0;
myHeap = new minHeap();
}

public class minHeap
{
static protected Action[] heap;
static public int counter;
public minHeap()
{
counter = -1;
heap = new Action[1000000];
}

public Action Pop()
{
if (counter < 0)
{
Console.WriteLine("empty");
return new Action(0, 0, new Customer());
}
Action returnValue = heap[0];
heap[0] = heap[counter];
counter--;
heapify(0);
return (returnValue);
}

public void Push(Action a)
{
counter++;
heap[counter] = new Action(double.PositiveInfinity, 0, new Customer());
InsertKey(counter, a);
}

static void InsertKey(int i, Action a)
{
if (heap[i].TimeOfExecution < a.TimeOfExecution)
Console.WriteLine("should not have happened");
heap[i] = a;
while (i > 0 && heap[Parent(i)].TimeOfExecution > heap[i].TimeOfExecution)
{
Action temp = heap[i];
heap[i] = heap[Parent(i)];
heap[Parent(i)] = temp;
i = Parent(i);
}
}

最佳答案

minHeap 类型上的所有字段都是static。所以是的:它们是共享的——这就是 static 的意思。您可能想让它们成为非静态

可能您在使用 readonly 时使用了 static

关于c# - 一个由不同线程分别创建的对象仍然是共享的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53481171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com