linux下几种加锁方法的比较

在linux2.6.20内核下, 分别执行1000000次的加锁解锁操作, 记录锁: real    0m3.280s user    0m1.943s sys     0m1.216s 信号量锁 real    0m31.255s user    0m8.996s sys     0m21.111s pthread_mutex_t real    0m0.018s user    0m0.015s sys     0m0.003s 与stevens在APUE里记述的结果恰好相反。 源代码如下:
#include 
#include 
#include 

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void test_filelock(int locktimes)
{
#include 
#include 
#include 

        struct flock lock, unlock;
        int count = 0;
        int fd;

        lock.l_type = F_WRLCK;
        lock.l_start = 0;
        lock.l_whence = SEEK_SET;
        lock.l_len = 1;

        unlock.l_type = F_ULOCK;
        unlock.l_start = 0;
        unlock.l_whence = SEEK_SET;
        unlock.l_len = 1;

        fd = open("lock.test", O_CREAT);

        for (count = 0; count < locktimes; ++count){
                fcntl(fd, F_SETLKW, &lock);
                fcntl(fd, F_SETLKW, &unlock);
        }
}

void test_pthread_lock(int locktimes)
{
        int i;
        for (i = 0; i < locktimes; ++i){
                pthread_mutex_lock(&mutex);
                pthread_mutex_unlock(&mutex);
        }
}

void test_semlock(int locktimes)
{
#include 
#include 
#include 
#include 

        struct sembuf bufLock, bufUnlock;
        int iCount = 0;

        int semid = semget(0x33332222, 1, IPC_CREAT|0666);

        if (semid == -1){
                printf("semget error/n");
                return ;
        }

        semctl(semid, 0, SETVAL, 1);

        bufLock.sem_num = 0;
        bufLock.sem_op = -1;
        bufLock.sem_flg = SEM_UNDO;

        bufUnlock.sem_num = 0;
        bufUnlock.sem_op = 1;
        bufUnlock.sem_flg = SEM_UNDO;

        for ( iCount = 0; iCount < 10000000; ++iCount){
                semop(semid, &bufLock, 1);
                semop(semid, &bufUnlock, 1);
        }
}

int main(int argc, char **argv)
{
        if(argc != 3){
                printf("usage: test_lock file|sem|pthread locktimes/n");
                exit(1);
        }

        int locktimes = atoi(argv[2]);
        if(strcmp(argv[1], "file") == 0)
                test_filelock(locktimes);
        else if(strcmp(argv[1], "sem") == 0)
                test_semlock(locktimes);
        else
                test_pthread_lock(locktimes);

        return 0;
}

另外,如果只需要一把锁的话,flock使用更方便,效率上于记录锁基本相同  

你可能感兴趣的:(linux下几种加锁方法的比较)