ref: 531ccfc4a563bbb29914d737ced61d39545c5107
dir: /lock.c/
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #include "bench.h" #define NLockIters 1 pthread_mutex_t l = PTHREAD_MUTEX_INITIALIZER; static int count; void nop(void) { } void work(void) { int i; for(i = 0; i < 100*1000; i++) count++; } void dolock(void (*work)(void), int n) { int i; for(i = 0; i < n; i++){ pthread_mutex_lock(&l); work(); pthread_mutex_unlock(&l); } } struct thread_data { void (*fn)(void(*)(void), int); void (*work)(void); int ninc; sem_t *start_sem; }; static void * thread_worker(void *arg) { struct thread_data *td = arg; sem_wait(td->start_sem); td->fn(td->work, td->ninc); return NULL; } void lockbench(void (*fn)(void(*)(void), int), int nthr, void (*work)(void), int ninc) { pthread_t *threads; struct thread_data td; sem_t start_sem; int i; threads = malloc(nthr * sizeof(pthread_t)); sem_init(&start_sem, 0, 0); td.fn = fn; td.work = work; td.ninc = ninc; td.start_sem = &start_sem; for(i = 0; i < nthr; i++){ if(pthread_create(&threads[i], NULL, thread_worker, &td) != 0) { fprintf(stderr, "pthread_create failed\n"); exit(1); } } for(i = 0; i < nthr; i++) sem_post(&start_sem); for(i = 0; i < nthr; i++) pthread_join(threads[i], NULL); sem_destroy(&start_sem); free(threads); } void benchlock1(B *b) { lockbench(dolock, 1, nop, b->N); } void benchlock4(B *b) { lockbench(dolock, 4, nop, b->N); } void benchlock16(B *b) { lockbench(dolock, 16, nop, b->N); } void benchlock64(B *b) { lockbench(dolock, 64, nop, b->N); } void benchlock512(B *b) { lockbench(dolock, 512, nop, b->N); } void benchlock1_w(B *b) { lockbench(dolock, 1, work, b->N); } void benchlock4_w(B *b) { lockbench(dolock, 4, work, b->N); } void benchlock16_w(B *b) { lockbench(dolock, 16, work, b->N); } void benchlock64_w(B *b) { lockbench(dolock, 64, work, b->N); } void benchlock512_w(B *b) { lockbench(dolock, 512, work, b->N); } int main(int argc, char **argv) { benchinit(argc, argv); printf("== locking (fast work) ==\n"); BM(benchlock1); BM(benchlock4); BM(benchlock16); BM(benchlock64); BM(benchlock512); printf("== locking (slow work) ==\n"); BM(benchlock1_w); BM(benchlock4_w); BM(benchlock16_w); BM(benchlock64_w); BM(benchlock512_w); return 0; }