pthread

Reference:

  1. 小雞的故事: [Linux pthread] joinable thread or detached thread?
  2. Joinable And Detached Threads
  3. 好好理解:关于线程资源的释放: pthread_join, pthread_exit, pthread_detach
  4. man7.org > Linux > man-pages: pthread_detach()
  5. pthread_cleanup_push与pthread_cleanup_pop的目的(作用)
  6. 线程取消(pthread_cancel)

pthread have two states:

  1. joinable: Resources of thread will not be automatically released to the system when thread terminates. (By default, created threads are joinable.)

  2. detached: Resources of thread will be automatically released to the system when thread terminates.

Release resources of thread:

1. Use pthread_join() (for joinable thread):

void* thread1()
{
    //do something
    pthread_exit((void *)5566);
}

int main()
{
    pthread_t thread_id;
    void *ret;

    pthread_create(&thread_id, NULL, thread1, NULL);
    pthread_join(thread_id, &ret);  
    return 0;
}

2. Set attribute of thread to detached when using pthread_create() (for detached thread)

void* thread1()
{
    //do something
    pthread_exit((void *)5566);
}

int main()
{
    pthread_t thread_id;
    pthread_attr_t attr_p; 

    pthread_attr_init(&attr_p);
    pthread_attr_setdetachstate(&attr_p, PTHREAD_CREATE_DETACHED); 
    pthread_create(&thread_id, &attr_p, thread1, NULL); 
    pthread_attr_destroy(&attr_p); 
    return 0;
}

3. Call pthread_detached() after pthread_creat()

void* thread1()
{
    //do something
    pthread_exit((void *)5566);
}

int main()
{
    pthread_t thread_id;

    pthread_create(&thread_id, NULL, &thread1, NULL);
    pthread_detach(thread_id); 
    return 0;
}

4. Call pthread_detached(pthread_self()) in thread function:

void* thread1()
{
    pthread_detach(pthread_self()); 
    //do something
    pthread_exit((void *)5566);
}

int main()
{
    pthread_t thread_id;

    pthread_create(&thread_id, NULL, &thread1, NULL);
    return 0;
}

results matching ""

    No results matching ""