首页 > 解决方案 > Do I have to return `NULL` for thread function when I use the detached pthread in linux?

问题描述

For example:

void* thread(void *arg)
{
    return NULL;
}

int main()
{
    pthread_attr_t attr;
    pthread_t th;
    pthread_attr_setdetachstate(pthread_attr_t &attr, PTHREAD_CREATE_DETACHED);
    pthread_create(&th, &attr, thread, NULL);
}

Because of it's a detached thread, I can not receive the funtion retrun by pthread_join. So I think the return of thread is useless, should I return NULL? If I don't return NULL, will it cause some bug?

标签: c++linuxpthreads

解决方案


should I return NULL?

You can return nullptr or any other value whether the thread is detached or not.

If I don't return NULL, will it cause some bug?

If you don't return anything then the behaviour of the program will be undefined.

P.S. The C++ standard library has portable wrappers for threads which allow you to not depend on any particular operating system. I recommend using those instead of system specific API.


推荐阅读