简体   繁体   中英

in pthread_create(), behavior when args is freed before the created thread exits

In pthread_create( *thread, *attr, *start_routine, *arg) , if arg is freed before the created thread exits, what is the behaviour? I didn't see it described in the specification from Open Group, so it may very well be undefined, I just can't find a place to confirm either way.

There's nothing special about pthread in this regard, so you'll not find a specific confirmation of this in the specs. from Open Group.

Your code is the only code that is going to de-reference the arg passed to pthread_create, you're responsible for its use and its lifetime. At least this can be reasonably assumed by the virtue of the argument being a void * , which a pthread implementation wouldn't know how to safely dereference, and the documentation for pthread_create giving no indication that it would inspect the argument to the thread routine.

If you pass in a dynamically allocated object and use it after it's freed, or pass in a pointer to an object whose lifetime has ended, using that object is undefined behavior, otherwise there is not a problem. There's nothing specific about that regarding pthreads or the arg argument to pthread_create.

Freeing args, means that your program can use that memory location as it wants. Address of args was sent in thread function, meanwhile if your program doesn't touch that memory location(which means value is still there) you will have wanted behavior inside thread, if it does touch, you will have undefined. So overall, freeing args will produce undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM