0

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

在函数 myThread.

我不断将 1、3 或 5 附加到 *x->value 的输出中

另外...如果我放置

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;
}
4

0 回答 0