CAS锁与MUTEX锁性能测试

来源:互联网 发布:java项目流程怎么说 编辑:程序博客网 时间:2024/05/30 04:50


#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;}


原创粉丝点击