Skip to content

Commit

Permalink
Fix bug in bench thread barrier
Browse files Browse the repository at this point in the history
The origin version cannot guarantee all the thread starting
kecho task at the same time. Because the main thread
may acquire mutex lock before all the bench_worker have
acquire it.

Change the barrier condition by using counting:
- Change condition variable to int n_retry for counting
- The worker acquire lock to add up the counting and wait
- The last worker reach the condition and broadcast the message
  • Loading branch information
kevinshieh0225 committed May 3, 2022
1 parent c678908 commit b31459c
Showing 1 changed file with 11 additions and 17 deletions.
28 changes: 11 additions & 17 deletions bench.c
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ static const char *msg_dum = "dummy message";
static pthread_t pt[MAX_THREAD];

/* block all workers before they are all ready to benchmarking kecho */
static bool ready;
static int n_retry;

static pthread_mutex_t res_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t worker_lock = PTHREAD_MUTEX_INITIALIZER;
Expand All @@ -83,12 +83,16 @@ static void *bench_worker(__attribute__((unused)))

/* wait until all workers created */
pthread_mutex_lock(&worker_lock);
while (!ready)
if (pthread_cond_wait(&worker_wait, &worker_lock)) {
puts("pthread_cond_wait failed");
exit(-1);
}
if (++n_retry == MAX_THREAD)
pthread_cond_broadcast(&worker_wait);
else
while (n_retry < MAX_THREAD)
if (pthread_cond_wait(&worker_wait, &worker_lock)) {
puts("pthread_cond_wait failed");
exit(-1);
}
pthread_mutex_unlock(&worker_lock);
/* all workers are ready, let's start bombing the server */

sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd == -1) {
Expand Down Expand Up @@ -140,20 +144,10 @@ static void create_worker(int thread_qty)
static void bench(void)
{
for (int i = 0; i < BENCH_COUNT; i++) {
ready = false;
n_retry = 0;

create_worker(MAX_THREAD);

pthread_mutex_lock(&worker_lock);

ready = true;

/* all workers are ready, let's start bombing kecho */
pthread_cond_broadcast(&worker_wait);

pthread_mutex_unlock(&worker_lock);

/* waiting for all workers to finish the measurement */
for (int x = 0; x < MAX_THREAD; x++)
pthread_join(pt[x], NULL);

Expand Down

0 comments on commit b31459c

Please sign in to comment.