由不同线程分别创建的对象仍然共享

时间:2018-11-26 12:30:16

标签: c# parallel.foreach

我有一个要在其中模拟队列的程序。为了加快处理速度(很多不同的参数),我以为可以使用并行循环,但是队列对象(或至少该对象内的对象)仍是共享的,尽管它们都是在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);
        }
    }

1 个答案:

答案 0 :(得分:5)

您的static类型的所有字段均为static。是的:它们是共享的-这就是static的意思。您可能希望将它们设置为非static

也许您是说readonly时使用过import numpy as np dWhy = np.random.sample(300) dby = np.random.sample(300) ps = np.random.sample(100000) targets = np.random.sample(100000) hs = np.random.sample(100000) dWhy += np.dot(ps,hs) dby += np.sum(ps) 吗?