1

大家早上好,

我试图用一个线程创建一个非常简单的应用程序,它会简单地更改对象变量的值,然后将其打印在屏幕上。所以现在每当我运行程序时,线程都会正确初始化,但是它会返回一些垃圾值object->a

你能否给我一些关于如何让这个工作的指示?

非常感谢。亚历克斯

HANDLE hPrintMutex;
int ThreadNr;

class object
{
    public:
        int a;
        object(void);
};

object::object(void)
{
    a=1;
}


void printNumber(void * arg)
{
    object * x=(object*) arg;
    std::cout<<"Thread1 -> "<< x->a<<"\n";;
    while(x->a<10)
    {
        WaitForSingleObject(hPrintMutex,INFINITE);
        x->a=5;
        ReleaseMutex(hPrintMutex);
    }
}

int main()
{
    object * Object; 
    Object = new object;

    hPrintMutex=CreateMutex(NULL,false,NULL);
    std::cout << "Main -> "<<Object->a<<"\n";

    HANDLE hThread1=(HANDLE)_beginthread(printNumber,0,&Object);

    WaitForSingleObject(hThread1,INFINITE);
    return 0;
}
4

1 回答 1

3

您正在传递object **给线程,但将其视为object *

你不需要&

HANDLE hThread1=(HANDLE)_beginthread(printNumber,0,&Object);
                                                   ^
于 2013-06-26T09:42:11.917 回答