Question

Question:

  • How to pass specifically two arguments to CreateThread, when:

    • Argument one, of type SOCKET
    • Argument two, an interface pointer:

    _COM_SMARTPTR_TYPEDEF(Range, __uuidof(Range));

    RangePtr pRange; //pass pRange

Suggestions:

Was it helpful?

Solution

create a structure of these two types and pass a pointer to it. This is the standard way of passing data to threads over single pointer.

OTHER TIPS

Rather than creating struct_thread_xyz_params, I would first use boost::thread if possible. If that wasn't an option, I would create a wrapper template function object that calls CreateThread with itself when it is constructed:

template <class Func>
class Thread
{
    Func m_Func;
    static DWORD WINAPI ThreadFunc(void* param)
    {
        Thread& pFunc = *(Thread*)param;
        pFunc();
        return S_OK;
    }
public:
    Thread(Func& func): m_Func(func){
        CreateThread(NULL,NULL,Thread::ThreadFunc,this,NULL,NULL);
    };
    void operator()()
    {
        m_Func();
    }
};

then if I had a function that took two args:

void printTwoStrings(string a, string b)
{
    cout << a << " " << b << endl;
};

I could wrap them in a functor:

class StringFunc
{
    string m_a;
    string m_b;
public:
    StringFunc(string a, string b):m_a(a),m_b(b)
    {

    };
    void operator()(){
        printTwoStrings(m_a,m_b);
    }
};

and initiliaze an instance of that functor on demand:

int main()
{

    Thread<StringFunc> myThread(StringFunc("hello","world"));
    Sleep(500);
    return 0;
}

note that I'm sleeping at the end, you didn't say anything at all about waiting for the thread to complete... The difficulty with struct_xyz_params is that you will often need later struct_wxyz_params and the temptation to duplicate code is always high...

boost::thread is good too (but I already said that).

-Rick

std::pair is your friend.

you could also post a WM_COPYDATA, filling a COPYDATASTRUCT at a later point after the thread is started (ref: http://msdn.microsoft.com/en-us/library/ms649011(VS.85).aspx)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top