You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

The C Standard, Section 7.26.5.6 [ISO/IEC 9899:2011], specifically states that a thread shall not be joined once it was previously joined or detached.  Similarly, in Section 7.26.5.3, it states that a thread shall not be detached once it was previously joined or detached.

Noncompliant Code Example

The following code example exhibits undefined behavior by detaching a thread that is later joined.  Performing this action can lead to undefined behavior.

#include <threads.h>
 
int thread_func(void *arg) {
  /* Do work */
  thrd_detach(thrd_current());
  return 0;
}

int main(void) {
  thrd_t t;

  if (thrd_success != thrd_create(&t, thread_func, 0)) {
    /* Handle error */
    return 0;
  }

  if (thrd_success != thrd_join(t, 0)) {
    /* Handle error */
    return 0;
  }

  return 0;
}

Compliant Solution

 In this compliant solution, the thread is not detached.  Its resources are released upon successfully joining with the main thread.

#include <threads.h>
  
int thread_func(void *arg) {
  /* Do work */
  return 0;
}

int main(void) {
  thrd_t t;

  if (thrd_success != thrd_create(&t, thread_func, 0)) {
    /* Handle error */
    return 0;
  }

  if (thrd_success != thrd_join(t, 0)) {
    /* Handle error */
    return 0;
  }

  return 0;
} 

Risk Assessment

Joining or detaching a previously joined or detached thread causes undefined behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON41-C

low

likely

low

P9

L2

Bibliography

[ISO/IEC 9899:2011]

Section 7.26.5.3, "The thrd_detach function"
Section 7.26.5.6, "The thrd_join function"

  • No labels