...
Canceling asynchronously would follow the same route as passing a signal in to the thread to kill it, thus posing similarities to POS44-C. Do not use signals to terminate threads, which is strongly related to SIG02-C. Avoid using signals to implement normal functionality. These expand on the dangers of canceling a thread suddenly as this can create a data race condition.
Noncompliant Code Example
In this noncompliant code example the worker thread is doing something as simple as swapping a and b repeatedly.
...
This code is thread-safe in that it invokes no undefined behavior. However, this program can still create a race condition, because an asynchronous cancel can happen at any time. For instance, the worker thread could be cancelled right before the last line (a = c) and thereby lose the old value of b. Consequently the main thread might print that a and b have the same value.
Compliant Solution
From IEEE standards page:
The cancelability state and type of any newly created threads, including the thread in which main() was first invoked, shall be PTHREAD_CANCEL_ENABLE and PTHREAD_CANCEL_DEFERRED respectively.
...
Since this code limits cancellation of the worker thread to the end of the while loop, the worker thread can preserve the data invariant that a == b. Consequently, the program might print that a and b are both 5, or they are both 10, but they will always be revealed to have the same value when the worker thread is cancelled.
Risk Assessment
Incorrectly using threads that asynchronously cancel may result in silent corruption, resource leaks and, in the worst case, unpredictable interactions.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
POS47-C | medium | probable | low | P12 | L1 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
In Java, similar reasoning resulted in the deprecation of Thread.stop() and appears in the Java Secure Coding Standard as CON24-J. Do not use Thread.stop() to terminate threads .
References
| Wiki Markup |
|---|
\[[MKS|AA. References#MKS]\] [{{pthread_cancel()}} Man Page|http://www.mkssoftware.com/docs/man3/pthread_cancel.3.asp]
\[[Open Group 04|AA. References#Open Group 04]\] [Threads Overview|http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_09.html] |