assert() safety in multithreaded context
Asked Answered
C

3

6

so I cannot seem to find solid info on whether assert is useable in a mulththreaded context.

logically to me it seems if an assertion fails the thread get shutdown but not the other threads?

or does the entire process get killed?

so basically my question. is it safe to use assert in a multithreaded environment without leaking resources?

Collectivity answered 20/11, 2014 at 12:4 Comment(3)
without leaking resources assert() terminate the program forcibly. Whether multithreaded or singlethreaded, you cannot free your resource. Basically, it's just for debugging. Do you really need to free resources?Emilemile
Where did you look for this "solid info"? Is the man page not clear that it "terminates the program by calling abort"?Assyrian
I was under the impression that threads do not get terminated at program shutdown if the function the thread is performing has not terminated.Collectivity
T
7

if you see the man page of assert(), it clearly states,

The purpose of this macro is to help the programmer find bugs in his program. The message "assertion failed in file foo.c, function do_bar(), line 1287" is of no help at all to a user.

This means, it's only useful [and should be used] in a developing environment, not in production software. IMO, in development stage, you need not to worry about leaks caused by assert(). YMMV.

Once you finished debugging your code, you can simply switch off the assert() functionality by defining [#define] NDEBUG.

Torsi answered 20/11, 2014 at 12:12 Comment(0)
J
3

I'd say more than yes. If I'd see a multithreaded code without asserts I'd not trust it. If you simplify a bit its implementations to something like:

#define assert(x) if( !(x) ) abort()

You'll see that it does nothing special for thread-safety or thread-specific. It's your responsibility to provide race-free condition and if the assertion fails, the whole process is aborted.

Jorgenson answered 20/11, 2014 at 12:19 Comment(0)
V
0

The entire process gets killed. Assert will send the expression, source filename and line number to stderr and then call abort(). Abort() terminates the entire process.

Vitta answered 15/9, 2021 at 20:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.