7 years, 6 months ago.

Does Thread object always have to be global?

Hi,

I had a code like this:

int main() {
    StartThread();

    while(1) {

    }
}

void StartThread() {
    Thread thread1;
    thread1.start(ThreadFunction);
}

void ThreadFunction() {
    while(1) {
        printf("MESSAGE");
    }
}

The above code does not work properly. I'd expect it to print "MESSAGE" in terminal infinietely.

When I modify it just a little bit, like this:

Thread thread1;

int main() {
    StartThread();

    while(1) {

    }
}

void StartThread() {
    thread1.start(ThreadFunction);
}

void ThreadFunction() {
    while(1) {
        printf("MESSAGE");
    }
}

it works as it should.

So, my question is, why does Thread object have to global? I'd rather create a new instance of Thread each time I call StartThread(). How to achieve that?

Be the first to answer this question.