Skip to content

A proposal to reduce synchronization overhead #1

@ANSI-Christ

Description

@ANSI-Christ

Currently, the worker function performs unnecessary actions:

void *worker(void *arg) {
  tpool *tp = (tpool *)arg;
  for (;;) {
    pthread_mutex_lock(&tp->tpool_lock);
    ......
    if (...) {
      ......
      pthread_mutex_unlock(&tp->tpool_lock);
      return NULL;
    }
    .........
    pthread_mutex_unlock(&tp->tpool_lock);

    j.f(j.arg); // run the job

    pthread_mutex_lock(&tp->tpool_lock);
    ......
    pthread_mutex_unlock(&tp->tpool_lock);
  }
}

you can rewrite code this way:

void *worker(void *arg) {
  tpool *tp = (tpool *)arg;

  pthread_mutex_lock(&tp->tpool_lock);
  for (;;) {
    ......
    if (...) {
      ......
      break;
    }
    .........
    pthread_mutex_unlock(&tp->tpool_lock);

    j.f(j.arg); // run the job

    pthread_mutex_lock(&tp->tpool_lock);
    ......
  }
  pthread_mutex_unlock(&tp->tpool_lock);
  return NULL;
}

thus, at each iteration of the loop, only 1 lock and 1 unlock occur

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions