将struct传递给_beginThreadEx()函数会产生意外的输出

时间:2012-10-18 19:18:35

标签: parameters struct beginthreadex

我正在尝试学习将多个参数传递给_beginThreadEx函数的“正确”方法。可以使用一些帮助。

功能myThread。

我继续在* x->值的输出中附加1,3或5

另外......如果我放置

cout << "die: " << random_num << endl;

之前

hThread[0] = (HANDLE)_beginthreadex(NULL, 0, myThread, &myThreadData, 0, NULL);

有时没有输出Hello World,所以我把它放在上面一行之后。

#include <iostream>
#include <process.h>
#include <stdint.h>
#include <time.h>
#include <string>
#include <windows.h>

#define PHI 0x9e3779b9

static uint32_t Q[4096], c = 362436;


using namespace std;

class cmwc
{
    public:

    void init_rand(uint32_t x)
    {
            int i;

            Q[0] = x;
            Q[1] = x + PHI;
            Q[2] = x + PHI + PHI;

            for (i = 3; i < 4096; i++)
                    Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i;
    }

    uint32_t rand_cmwc(void)
    {
            uint64_t t, a = 18782LL;
            static uint32_t i = 4095;
            uint32_t x, r = 0xfffffffe;
            i = (i + 1) & 4095;
            t = a * Q[i] + c;
            c = (t >> 32);
            x = t + c;
            if (x < c) {
                    x++;
                    c++;
            }
            return (Q[i] = r - x);
    }

};

struct myThreadStructure
{
    int *value;
    //~myThreadStructure() {delete[] string;}
};

unsigned __stdcall myThread(void *data)
{
    //C:\dev\default threads\_threads.cpp|6|error: invalid conversion from 'int*' to 'int' [-fpermissive]|

    //works?
    //int *x = static_cast<int*>(data);

    myThreadStructure *x = static_cast<myThreadStructure*>(data);

    //int *x = (int*)data;

    std::cout << "Hello World! " << *x->value << endl;
    _endthreadex(0);
}

int main()
{
    cmwc rng1;

    myThreadStructure myThreadData;

    rng1.init_rand(time(NULL));

    uint32_t random_num = 1 + rng1.rand_cmwc()%6;

    //int r = rng1.rand_cmwc();



    HANDLE hThread[4];

    int x = 10;

    myThreadData.value = &x;

    //works
    //hThread[1] = (HANDLE)_beginthreadex(NULL, 0, myThread, &x, 0, NULL);

    hThread[0] = (HANDLE)_beginthreadex(NULL, 0, myThread, &myThreadData, 0, NULL);

    WaitForMultipleObjects(0, hThread, TRUE, INFINITE);

    //delete [] myThreadData;

    cout << "die: " << random_num << endl;


    //while(true);
    return 0;
}

0 个答案:

没有答案