dubbeat
dubbeat

Reputation: 7857

How to Kill a waiting pthread

Have a pthread that sleeps while waiting on a condition variable. I use a boolean in the outer while loop to keep it running. The problem I seem to have is when I change this variable the thread does not die.

I took a look in instruments and if I start a thread , tell it to die, then start a new one my thread count is 2 not 1.

How can I properly destroy this thread when I want to?

int worktodo=0;
BOOL runthread=NO;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;


void *threadfunc(void *parm)

{
    int rc;


    while(runthread==YES)

    {
        rc=pthread_mutex_lock(&mutex);

        while(!worktodo)

        {
            printf("thtread blocked\n");
            rc=pthread_cond_wait(&cond, &mutex);

        }

        printf("thtread awake.... doing work\n");

        // doing work

        worktodo=0;

        rc=pthread_mutex_unlock(&mutex);



    }

    // never reaches here!!
    pthread_detach(NULL);


}



void makeThread()
{

pthread_attr_t  attr;

int             returnVal;

returnVal = pthread_attr_init(&attr);
assert(!returnVal);
runthread=YES;
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);

int     threadError = pthread_create(&str->thread, &attr, &threadfunc, NULL);

returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
    // Report an error.
}



}

void wakethread()
{

    pthread_mutex_lock(&mutex);

    worktodo=1;
    pthread_cond_signal(&cond);

    pthread_mutex_unlock(&mutex);

}

void killthread

{
  runthread=NO;

}

Upvotes: 0

Views: 607

Answers (2)

dubbeat
dubbeat

Reputation: 7857

thiton was correct. I couldnt kill the thread while it was blocked. Theres probably a better way to do this but the solution that worked for me was to set runthread to false then wake the thread.

void killthread

{
  runthread=NO;

  pthread_mutex_lock(&mutex);

    worktodo=1;
    pthread_cond_signal(&cond);

    pthread_mutex_unlock(&mutex);


}

Upvotes: 1

thiton
thiton

Reputation: 36059

You initialize runthread to NO and compare it to YES. The thread should never reach the inside of its

while(runthread==YES)

loop. Besides, when the thread waits for work, killthread will not wake it up and runthread will stay in its work-waiting loop.

Upvotes: 0

Related Questions