Created
December 6, 2021 11:02
-
-
Save aarzilli/eb414dd4a2c5cea6cda9825e50e1338b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <pthread.h> | |
int N = 100000; | |
//int N = 20; | |
pthread_mutex_t ping_lock = PTHREAD_MUTEX_INITIALIZER, pong_lock = PTHREAD_MUTEX_INITIALIZER; | |
pthread_cond_t ping_cond, pong_cond; | |
pthread_t ping_thread, pong_thread; | |
int can_ping = 1, can_pong = 0; | |
void *pingfunc(void *arg) { | |
int i; | |
for (i = 0; i < N; ++i) { | |
pthread_mutex_lock(&ping_lock); | |
while(!can_ping) { | |
pthread_cond_wait(&ping_cond, &ping_lock); | |
} | |
pthread_mutex_unlock(&ping_lock); | |
can_ping = 0; | |
//printf("ping!\n"); | |
pthread_mutex_lock(&pong_lock); | |
can_pong = 1; | |
pthread_cond_signal(&pong_cond); | |
pthread_mutex_unlock(&pong_lock); | |
} | |
} | |
void *pongfunc(void *arg) { | |
int i; | |
for (i = 0; i < N; ++i) { | |
pthread_mutex_lock(&pong_lock); | |
while(!can_pong) { | |
pthread_cond_wait(&pong_cond, &pong_lock); | |
} | |
pthread_mutex_unlock(&pong_lock); | |
can_pong = 0; | |
//printf("pong!\n"); | |
pthread_mutex_lock(&ping_lock); | |
can_ping = 1; | |
pthread_cond_signal(&ping_cond); | |
pthread_mutex_unlock(&ping_lock); | |
} | |
} | |
int main(void) { | |
struct timespec t0, t1; | |
clock_gettime(CLOCK_MONOTONIC, &t0); | |
pthread_cond_init(&ping_cond, NULL); | |
pthread_cond_init(&pong_cond, NULL); | |
pthread_create(&ping_thread, NULL, pingfunc, NULL); | |
pthread_create(&pong_thread, NULL, pongfunc, NULL); | |
pthread_join(ping_thread, NULL); | |
pthread_join(pong_thread, NULL); | |
clock_gettime(CLOCK_MONOTONIC, &t1); | |
double d = (double)(t1.tv_sec - t0.tv_sec) + 1.0e-9 * (double)(t1.tv_nsec - t0.tv_nsec); | |
printf("%.10f seconds per pingpong (total %.5f)\n", d/ N, d); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment