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 <pthread.h>
#include <stdlib.h>
#include <stdio.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void test_filelock(int locktimes)
{
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

        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 <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>

        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使用更方便,效率上于记录锁基本相同  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值