Visual C ++ / CLI中的线程程序给出了错误

时间:2013-07-11 12:05:06

标签: multithreading visual-studio-2010 visual-c++ c++-cli

我正在尝试按照http://www.drdobbs.com/cpp/ccli-threading-part-i/184402018中的教程在visual c ++中的winform中进行线程编程。我打开了一个win32控制台项目,并在其中添加了一个空的cpp文件,我在其中放置了如下代码:

    using namespace System;
    using namespace System::Threading;

    public class ThreadX{

        int loopStart;
        int loopEnd;
        int dispFrequency;

        public:


        ThreadX(int startValue, int endValue, int frequency)
        {
            loopStart = startValue;
            loopEnd = endValue;
            dispFrequency = frequency;
        }

        void ThreadEntryPoint()
        {
            String^ threadName = Thread::CurrentThread->Name;

            for (int i = loopStart; i <= loopEnd; ++i)
            {
                if ( i % dispFrequency == 0)
                {
                    Console::WriteLine("{0} : i = {1,10}", threadName, i);
                }
            }
            Console::WriteLine("{0} thread terminating", threadName);
        }
};

int main()
{
    ThreadX o1 = gcnew ThreadX(0, 1000000,200000);
    Thread^ t1 = gcnew Thread(gcnew ThreadStart(o1, &ThreadX::ThreadEntryPoint));
    t1->Name = "t1";

    ThreadX o2 = gcnew ThreadX(-1000000, 0, 200000);
    Thread^ t2 = gcnew Thread(gcnew ThreadStart(o2, &ThreadX::ThreadEntryPoint));
    t1->Name = "t2";

    t1->Start();
    t2->Start();
    Console::WriteLine("Primary Thread Terminating");
}

然而,这给了我错误,例如:

  1. 错误C2726:'gcnew'只能用于创建对象 托管类型
  2. 错误C2440:'初始化':不能 从'ThreadX *'转换为'ThreadX'没有构造函数可以使用 源类型或构造函数重载解析是不明确的
  3. 错误C3364:'System :: Threading :: ThreadStart':委托构造函数的参数无效;委托目标需要是一个 指向成员函数的指针

1 个答案:

答案 0 :(得分:1)

您正在混合C ++和C ++ / CLI,这是另一回事。取代

public class ThreadX

public ref class ThreadX