Main Content

MISRA C:2012 Rule 22.11

A thread that was previously either joined or detached shall not be subsequently joined nor detached

Since R2024b

Description

This checker is deactivated in a default Polyspace® as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).

Rule Definition

A thread that was previously either joined or detached shall not be subsequently joined nor detached

This rule comes from MISRA C™: 2012 Amendment 4.

Rationale

The C11 standard (clauses 7.26.5.3 and 7.26.5.6) states that a thread shall not be joined or detached once it was previously joined or detached. Violating these clauses of the standard results in undefined behavior.

Polyspace Implementation

Polyspace reports a violation of this rule when:

  • You try to join a thread that was previously joined or detached.

  • You try to detach a thread that was previously joined or detached.

The Result Details pane shows whether the thread was previously joined or detached and also shows previous related events.

Polyspace considers a thread joined only if a previous thread joining was successful. For instance, the thread t is not considered joined in the body of the if branch:

thrd_t t;
...
if (thrd_success != thrd_join(t, 0)) {
    /* Thread not considered joined */
} 
Polyspace cannot detect cases where a joined thread detaches itself, for example, by using the thrd_current() function.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, a thread is joined by using thrd_join() and then detached by using thrd_detach(), which leads to undefined behavior. Polyspace reports a violation of this rule.

#include <stddef.h>
#include <threads.h>
#include <stdlib.h>


extern int thread_func(void *arg);

int main(void)
{
	thrd_t t;

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

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

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

	return 0;
}

To avoid compilation errors when running Bug Finder on this example, specify the C11 standard by using the option C standard version (-c-version).

Correction – Avoid Detaching a Joined Thread

Remove the call to thrd_join() or the call to thrd_detach(). In this corrected version, the call to thrd_detach() is removed.

#include <stddef.h>
#include <threads.h>
#include <stdlib.h>


extern int thread_func(void *arg);

int main(void)
{
	thrd_t t;

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

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

	return 0;
}

Check Information

Group: Resources
Category: Required
AGC Category: Required

Version History

Introduced in R2024b