CERT.POS.THREAD.ASYNC_CANCEL

Do not use threads that can be canceled asynchronously.

Vulnerability and risk

In threading, pthreads can optionally be set to cancel immediately or defer until a specific cancellation point. Canceling asynchronously (immediately) is dangerous, however, because most threads are in fact not safe to cancel immediately. For example, canceling asynchronously can result in locks/mutexes not being released.

Mitigation and prevention

Don't pass PTHREAD_CANCEL_ASYNCHRONOUS to pthread_setcanceltype(). Use pthread_testcancel() in a thread to test for cancellation when it is safe to stop the thread.

Example

Copy
if ((result = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&i)) != 0) {
    /* handle error */
  }

A violation will be reported on line 1.