• System V semaphore——demo


    代码
    #include sys/types.h>
    #include sys
    /ipc.h>
    #include sys
    /sem.h>
    union semun{
    int val;
    struct semid_ds *buf;
    unsigned
    short *array;
    struct seminfo *__buf;
    };

    // create the semaphore set,
    // if key is IPC_PRIVATE, the semaphore is anonymous
    int semaphore_create(key_t key, int number)
    {
    return semget(key, number, IPC_CREAT|IPC_EXCL|0666);
    }

    // set all semaphores to val
    int semaphore_setAll(int semid, int number, int val)
    {
    int i;
    union semun initVal;
    unsigned
    short valList[number];
    for (i = 0; i < number; i++)
    {
    valList[i]
    = val;
    }
    initVal.array
    = &valList[0];
    return semctl(semid, 0, SETALL, initVal);
    }

    // get all semaphores to val
    int semaphore_getAll(int semid, unsigned short** val)
    {
    union semun ret;
    ret.array
    = *val;
    return semctl(semid, 0, GETALL, ret);
    }

    // set index-th semaphore to val
    int semaphore_set(int semid, int index, int val)
    {
    union semun un;
    un.val
    = val;
    return semctl(semid, index, SETVAL, un);
    }

    // get index-th semaphore to val
    int semaphore_get(int semid, int index, int *val)
    {
    union semun un;
    un.val
    = *val;
    return semctl(semid, index, GETVAL, un);
    }

    // delete the semaphore set
    int semaphore_del(int semid)
    {
    return semctl(semid, 0, IPC_RMID);
    }

    // v operation, here we just add one for example
    int semaphore_v(int semid, int index)
    {
    // add the semaphore
    struct sembuf operation;
    operation.sem_num
    = index;
    operation.sem_op
    = 1;
    operation.sem_flg
    = SEM_UNDO;
    return semop(semid, &operation, 1);
    }

    // p operation, here just del one for example
    int semaphore_p(int semid, int index)
    {
    struct sembuf operation;
    operation.sem_num
    = index;
    operation.sem_op
    = -1;
    operation.sem_flg
    = SEM_UNDO;
    struct timespec delay;
    delay.tv_sec
    = 2;
    delay.tv_nsec
    = 0;
    return semtimedop(semid, &operation, 1, &delay);
    }
  • 相关阅读:
    python基础之函数
    MySQL 安装 5.0
    MySQL安装 MySQL5.7.10免安装版配置,mysql5.7.10免安装版
    安装MYSql Windows7下MySQL5.5.20免安装版的配置
    网站集合
    andorid 开放工具集合
    Win7 x64 Eclipse无法识别手机 / adb interface有黄色感叹号,无法识别
    字符集 ISO-8859-1(3)
    字符集 ISO-8859-1(2)
    字符集 ISO-8859-1(1)
  • 原文地址:https://www.cnblogs.com/BloodAndBone/p/1939518.html
Copyright © 2020-2023  润新知