George Irimiciuc
George Irimiciuc

Reputation: 4633

Creating a thread

I know I can create a thread within a program with CreateThread() and I need to WaitForSingleObject() for it to finish before returning to the original program.

My question is, is the original program a thread as well? Say, I have a variable a=3 in my program, then I create a thread. From the second thread, can I get access to my variable a?

Upvotes: 0

Views: 98

Answers (3)

harper
harper

Reputation: 13690

When the Windows O/S starts a process it will also create the first thread for that process.

So, the "original program" is the wrong name. But the initial item the is executing the progra m is a thread.

When your variable scope allows the access from the second thread than you can access it. If you want to pass access to a specific variable you can use the appropriate parameter to CreateThread to pass a pointer to it. But beware: When the execution of the original thread goes out of the scope of this variable then the pointer gets invalid. I recommend to consider a redesign.

Edit As requested, here is a example for variable going a out of scope. This would be a wrong implementation:

DWORD TheThread(void*p)
{
    int *pcounter = (int*)p;
    // do anything with pcounter
}

HANDLE MakeItRun()
{
    int counter;
    return CreateThread(0, 0, &TheThread, &counter, 0, 0);
} // scope of counter ends here

int main()
{
    HANDLE h;
    h = MakeItRun();
    WaitForSingleObject(h, INFINITE);
}

Upvotes: 1

japreiss
japreiss

Reputation: 11251

This won't work:

DWORD WINAPI threadProc(LPVOID param)
{
    a = 5;
}

int main()
{
    int a = 3;
    HANDLE thread = CreateThread(NULL, 0, threadProc, NULL, 0, NULL);
    WaitForSingleObject(thread, INFINITE);
}

The compiler will issue an error telling you that a is undeclared in threadProc.

You can pass a pointer though:

DWORD WINAPI threadProc(LPVOID param)
{
    int *aPtr = (int *)param;
    *aPtr = 5;
}

int main()
{
    int a = 3;
    HANDLE thread = CreateThread(NULL, 0, threadProc, &a, 0, NULL);
    WaitForSingleObject(thread, INFINITE);
    // value of a is now 5
}

This is a perfectly correct technique, as long as you ensure that the scope of the stack variable outlives the thread.

You can also share memory between threads with global variables or their alternate forms (singleton classes, static class variables).

Upvotes: 1

Martin James
Martin James

Reputation: 24907

Yes - a thread is the OS fundamental unit of execution. No threadee, no runnee.

Upvotes: 0

Related Questions