aluminumMonster
aluminumMonster

Reputation: 75

Cancelling A Thread Safely

I have C code in main that creates 10 threads. Then I join for those threads.

Each thread goes to a function like this:

void test_function(char *findThis)
{
    // do something

    // then something like this
    if message cancel thread?
}

The message would probably be a Boolean global variable. How do I cancel the thread afterwards?

Upvotes: 0

Views: 74

Answers (1)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29186

In C, a thread executes a particular function. If you return from that function, it no longer exists.

So, simply return from that function if you want your thread to stop, like this -

if (got_my_message) {
    return;
}

Of course, you should perform necessary resource clean up (i.e., free up allocated memory) before you do so.

Upvotes: 1

Related Questions