Closed thiefuniverse closed 7 years ago
Looks like your test case is going out of its way to run JSON parsing after main has returned. Is that something you need for a real-world use case? Why not join the thread before the process exits?
In general, a lot of code can become unsafe if it's run before main starts, or after main exits (or after a call to exit() or similar). My guess is that this crash is occurring because static variables are destroyed after main exits, and thus can't be safely used anymore. Json11 does depend on some static state, constructed here: https://github.com/dropbox/json11/blob/master/json11.cpp#L238
Thanks firstly, I think probably it's that problem. I develop a SDK and when user load my lib a thread will parse json all the time. I detach this thread when its created. So sometimes if user's main thread exits my child thread will run to Json::parse function and crash. Do you have some suggestions? I can't control the time when user exits so I can't use join, I think.
Two possible answers for you:
1) If your SDK is making use of background threads, and you want to support clean termination, then I'd suggest providing your SDK user with an explicit shutdown()
function to call to perform cleanup by terminating threads, freeing resources, etc. I'd consider including such a function in any library which managed background threads, regardless of this parsing situation. There's always the potential for unexpected results if a thread isn't terminated cleanly before exit, and an explicit shutdown would also give your user the option to stop their threads if they're unneded for a while. Note that if the process terminates uncleanly (e.g. with a crash or a call to terminate()
) your shutdown might not get called, but if the process is already crashing anyway that's likely not a big deal.
2) Building a library to be safe to use during exit puts some additional requirements on it which json11 wasn't designed to meet. Json11 was initially built for use on mobile, where processes mostly don't ever exit (they just get suspended or killed), so this wasn't ever a priority. If you decide you need those requirements you might need to try a different library which has no global data. You could also take a stab at forking and removing the global data requirements from json11, since I believe they're mostly performance/memory optimizations.
Thanks very much for your suggestions. I tried to use nlohmann/json for my example and it exited normally and I will test it at my SDK (I have no confidence for modifying this lib). I also will consider to add a interface for releasing resource. Really thanks! :smile:
Hello, I use Json::parse in the child thread and I find that my program will crash at Json::parse in a child thread.
And This is my backtrace using gdb with a core dump file.
Maybe it's a destruction problem of shared_ptr or my usage problem ? Thanks for your help! :)