【问题标题】:How do I properly manage the lifetime of a Qubit in C#如何在 C# 中正确管理 Qubit 的生命周期
【发布时间】:2018-06-30 16:07:09
【问题描述】:

我正在玩 Q#,它使用 C# 作为驱动程序。我想将一个 Qubit 对象传递给 Q# 代码,但它没有按预期工作。

C# 驱动程序

using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;

namespace Quantum.QSharpApplication1 {
    class Driver {
        static void Main(string[] args) {
            using (var sim = new QuantumSimulator()) {
                var x = new Microsoft.Quantum.Simulation.Common.QubitManager(10);
                Qubit q1 = x.Allocate();
                Solve.Run(sim, q1, 1);
                }
            System.Console.WriteLine("Press any key to continue...");
            System.Console.ReadKey();
            }
        }
    }

问#

namespace Quantum.QSharpApplication1
{
    open Microsoft.Quantum.Primitive;
    open Microsoft.Quantum.Canon;

    operation Solve (q : Qubit, sign : Int) : ()
    {
        body
        {
            let qp = M(q);
            if (qp != Zero)
            {
                X(q);
            }     
            H(q);
        }
    }
}

当我运行它时,它会正常运行,直到到达 System.Console.* 行,此时它会在 Q# 代码中引发以下异常

System.AccessViolationException
  HResult=0x80004003
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

调试器将此与“let qp = M(q);”相关联Q# 中的一行。

请注意,这确实发生在 Solve.Run 调用中,实际代码有多个 Solve 调用,并且输出显示正确。它只出现在使用 QuantumSimulator 范围离开之后。我记得读过 Qubit 在发布之前必须重置为零。我不确定这是否是这里的问题,但我看不到在 C# 中这样做的方法。有趣的是,我删除了 Console 行,程序将毫无错误地运行(计时?)。

【问题讨论】:

    标签: c# q#


    【解决方案1】:

    您用来创建量子位的QubitManager 实例不是单例(每个Simulator 都有自己的QubitManager),因此Simulator 不知道您试图在其上操纵的Qubit Q# 代码,即AccessViolationException

    一般来说,不支持在驱动上创建量子位;您可以在 Q# 中使用 only allocate qubits using the allocate and borrowing 语句。建议在 Q# 中创建一个入口点来分配执行 qubit 分配的 qubits,并从驱动程序中调用它,例如:

    // MyOp.qs
    operation EntryPoint() : () 
    {
        body
        {
            using (register = Qubit[2]) 
            {
                myOp(register);
            }
        }
    }
    
    
    // Driver.cs
    EntryPoint.Run().Wait();
    

    最后,请注意,在您的驱动程序代码中,您有以下内容: Solve.Run(sim, q1, 1);

    Run 方法返回一个异步执行的任务。您通常必须添加 Wait() 以确保它完成执行: EntryPoint.Run(sim, 1).Wait();

    如果您这样做,您会注意到Run 期间的失败,而不是Console.WriteLine

    【讨论】:

      猜你喜欢
      • 2012-12-28
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      相关资源
      最近更新 更多