CAS锁与MUTEX锁性能测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/junlon2006/article/details/77149479


#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/time.h>

#define lock(lkp) do{  \
    while(!__sync_bool_compare_and_swap(lkp, 0, 1)){    \
        usleep(1000); \
    }   \
}while(0)

#define unlock(lkp) do{    \
    *(lkp) = 0;  \
}while(0)

static unsigned long long count = 0;
static int lock = 0;

struct timeval start, end;
static pthread_mutex_t mutex;

void *test_func(void *arg)
{
    int i=0;
    for(i=0; i < 0xFFFFFFF; ++i) {
        lock(&lock);
        //pthread_mutex_lock(&mutex);
        count++;
        //pthread_mutex_unlock(&mutex);
        unlock(&lock);
    }

    return NULL;
}

int main(int argc, const char *argv[])
{
    pthread_t id[2];
    int i = 0;

    gettimeofday(&start, NULL);
    for(i=0; i < 2; ++i) {
        pthread_create(&id[i],NULL,test_func,NULL);
    }
    for(i=0; i < 2; ++i) {
        pthread_join(id[i],NULL);
    }

    gettimeofday(&end, NULL);
    printf("waste time = %lus, %luus\n", end.tv_sec - start.tv_sec, end.tv_usec - start.tv_usec);
    printf("%llu\n",count);
    return 0;
}


展开阅读全文

没有更多推荐了,返回首页