Passing struct to _beginThreadEx() function produces unintended output

1k views Asked by At

I'm trying to learn the "proper" way of passing multiple parameters to a _beginThreadEx function. Could use some help.

In function myThread.

I keep getting either a 1, or 3, or 5 appended to the output of *x->value

Also... if I place

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

before

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

sometimes there is no Hello World outputted, so instead I place it after the above line.

#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

There are 0 answers