Pthread create as detached

Manlio picture Manlio · Jun 1, 2011 · Viewed 32.7k times · Source

I have a problem creating a thread as detached. Here's the code I wrote:

void* testFunction() {

    pthread_attr_t attr;
    int chk,rc;

pthread_attr_init(&attr);
printf("thread_attr_init: %d\n",rc);

pthread_attr_getdetachstate(&attr, &chk);
printf("thread_attr_getdetachedstate: %d\n",rc);

if(chk == PTHREAD_CREATE_DETACHED ) 
    printf("Detached\n");
else if (chk == PTHREAD_CREATE_JOINABLE) 
    printf("Joinable\n");

return NULL;
}


int main (int argc, const char * argv[]) {

pthread_t thread1;
pthread_attr_t attr;

int rc;

rc = pthread_attr_init(&attr);

printf("attr_init: %d\n",rc);
rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
printf("attr_setdetachedstate: %d\n",rc);

rc = pthread_create(&thread1, &attr, testFunction, NULL);
printf("attr_create: %d\n",rc);

sleep(4);
pthread_cancel(thread1);

return 0;
}

The problem is that testFunction() always print "Joinable". Can anyone tell me where I'm getting wrong?

Answer

Your testFunction is not examining anything about the current thread, rather just the initially-detached flag of a completely new attribute object you just created. Moreover, it is completely impossible, in the POSIX threads API, to recover the attributes a thread was created with or determine if a thread is detached or not. You simply have to trust that the implementation behaves as required, just like you have to trust that, if malloc(100) returns a non-null pointer, it points to a location at which you can store at least 100 bytes. This is the nature of C.