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

Compare with Current View Page History

« Previous Version 10 Next »

A consistent locking policy guarantees that multiple threads cannot simultaneously access or modify shared data. When two or more operations must be performed as a single atomic operation, a consistent locking policy must be implemented using some form of locking, such as a mutex. In the absence of such a policy, the code is susceptible to race conditions.

When presented with a set of operations, where each is guaranteed to be atomic, it is tempting to assume that a single operation consisting of individually-atomic operations is guaranteed to be collectively atomic without additional locking. A grouping of calls to such methods requires additional synchronization for the group.

Compound operations on shared variables are also non-atomic. See rule CON42-C. Ensure that compound operations on shared variables are atomic for more information.

Noncompliant Code Example

This noncompliant code example stores two integers atomically. It also provides atomic methods to obtain their sum and product. All methods are locked with the same mutex to provide their atomicity.

 

Unfortunately, the multiply_monomials() function is still subject to race conditions, despite relying exclusively on atomic function calls. It is quite possible for get_sum() and get_product() to work with different numbers than the ones that were set by set_values(). It is even possible for get_sum() to operate with different numbers than get_product().

Compliant Solution

This compliant solution locks the multiply_monomials() function with the same mutex lock that is used by the other functions.

 

 

Noncompliant Code Example

Function chaining is a useful design pattern for building an object and setting its optional fields. The output of one function serves as an argument (typically the last) in the next function. However, if accessed concurrently, a thread may observe shared fields to contain inconsistent values. This noncompliant code example demonstrates a race condition that can occur when multiple threads can variables with no thread protection.

 

In this noncompliant code example, the program constructs a currency struct and starts two threads that use method chaining to set the optional values of the structure. This example code might result in the currency struct being left in an inconsistent state, for example, with two quarters and one dime or one quarter and two dimes.

Noncompliant Code Example

This code remains unsafe even if it uses a mutex on the set functions to guard modification of the currency.

 

Compliant Solution

This compliant solution uses a mutex, but instead of guarding the set functions, it guards the init functions, which are invoked by the threads.

typedef struct currency_s {
  int quarters;
  int dimes;
  int nickels;
  int pennies;
  mtx_t lock;
} currency_t;

currency_t *set_quarters(int quantity, currency_t *currency) {
  currency->quarters = quantity;
  return currency;
}
 
currency_t *set_dimes(int quantity, currency_t *currency) {
  currency->dimes = quantity;
  return currency;
}

currency_t *set_nickels(int quantity, currency_t *currency) {
  currency->nickels = quantity;
  return currency;
}
 
currency_t *set_pennies(int quantity, currency_t *currency) {
  currency->pennies = quantity;
  return currency;
}

void *init_30_cents(void *currency) {
  int result;
  if ((result = mtx_lock(&currency->lock)) != thrd_success) {
    /* handle error */
  }
  set_quarters(1, set_dimes(1, currency));
  if ((result = mtx_unlock(&currency->lock)) != thrd_success) {
    /* handle error */
  }
  return currency;
}

void *init_60_cents(void *currency) {
  int result;
  if ((result = mtx_lock(&currency->lock)) != thrd_success) {
    /* handle error */
  }
  set_quarters(2, set_dimes(2, currency));
  if ((result = mtx_unlock(&currency->lock)) != thrd_success) {
    /* handle error */
  }
  return currency;
}

int main(void) {
  int result;
  thrd_t thrd1;
  thrd_t thrd2;
  currency_t currency = {0, 0, 0, 0};

  if ((result = mtx_init(&currency.lock, mtx_plain)) != thrd_success) {
    /* Handle error */
  }
  if ((result = thrd_create(&thrd1, init_30_cents, &currency)) != thrd_success) {
    /* Handle error */
  }
  if ((result = thrd_create(&thrd2, init_60_cents, &currency)) != thrd_success) {
    /* Handle error */
  }

  if ((result = thrd_join(&thrd1, NULL)) != thrd_success) {
    /* Handle error */
  }
  if ((result = thrd_join(&thrd2, NULL)) != thrd_success) {
    /* Handle error */
  }

  printf("%d quarters, %d dimes, %d nickels, %d pennies\n",
         currency.quarters, currency.dimes, currency.nickels, currency.pennies);

  mtx_destroy(&currency.lock);
  return 0;
}

Consequently this compliant solution is thread-safe, and will always print out the same number of quarters as dimes.

Risk Assessment

Failure to ensure the atomicity of two or more operations that must be performed as a single atomic operation can result in race conditions in multithreaded applications.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON43-C

low

probable

medium

P4

L3

Related Guidelines

MITRE CWE

CWE-362. Concurrent execution using shared resource with improper synchronization ("race condition")

 

CWE-366. Race condition within a thread

 

CWE-662. Improper synchronization

CERT Java

VNA03-J. Do not assume that a group of calls to independently atomic methods is atomic

CERT JavaVNA04-J. Ensure that calls to chained methods are atomic

Bibliography

 

 

 

            

  • No labels