Difference between revisions of "Python"
From Tech
Jump to navigationJump to search (Replaced content with "* multiprocess.Lock replacement using SYSV") |
|||
Line 1: | Line 1: | ||
− | * [[multiprocess.Lock replacement using SYSV]] |
+ | * [[multiprocess.Lock replacement using SYSV]] |
− | <nowiki> |
||
− | #include <sys/types.h> |
||
− | #include <sys/ipc.h> |
||
− | #include <sys/sem.h> |
||
− | #include <stdlib.h> |
||
− | #include <stdio.h> |
||
− | |||
− | int acquire(int semid){ |
||
− | struct sembuf sops[2]; |
||
− | |||
− | sops[0].sem_num = 0; |
||
− | sops[0].sem_op = -1; |
||
− | sops[0].sem_flg = SEM_UNDO; |
||
− | |||
− | |||
− | if (semop(semid, sops, 1) == -1) { |
||
− | perror("acquire"); |
||
− | exit(1); |
||
− | } |
||
− | } |
||
− | |||
− | int release(int semid){ |
||
− | struct sembuf sops[2]; |
||
− | |||
− | sops[0].sem_num = 0; /* Operate on semaphore 0 */ |
||
− | sops[0].sem_op = 1; /* Wait for value to equal 0 */ |
||
− | sops[0].sem_flg = SEM_UNDO; |
||
− | |||
− | |||
− | if (semop(semid, sops, 1) == -1) { |
||
− | perror("release"); |
||
− | exit(1); |
||
− | } |
||
− | } |
||
− | |||
− | void p(int semid, int i){ |
||
− | int j; |
||
− | |||
− | acquire(semid); |
||
− | for(j=0; j<10; j++){ |
||
− | printf("%i\n",i); |
||
− | sleep(1); |
||
− | } |
||
− | release(semid); |
||
− | } |
||
− | |||
− | int main(int argc, char **argv){ |
||
− | key_t key; |
||
− | int semid; |
||
− | int wait_status; |
||
− | union semun { |
||
− | int val; /* Value for SETVAL */ |
||
− | struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ |
||
− | unsigned short *array; /* Array for GETALL, SETALL */ |
||
− | struct seminfo *__buf; /* Buffer for IPC_INFO |
||
− | (Linux-specific) */ |
||
− | }; |
||
− | int v; |
||
− | union semun su; |
||
− | |||
− | //key=ftok("l-.l", 0x55); |
||
− | //printf("key=%i\n",key); |
||
− | key=IPC_PRIVATE; |
||
− | semid=semget(key, 1, IPC_CREAT|0666); |
||
− | printf("semid=%i\n",semid); |
||
− | su.val=1; |
||
− | v=semctl(semid, 0, SETVAL, su); |
||
− | if(v==-1){ |
||
− | perror("semctl0"); |
||
− | exit(1); |
||
− | } |
||
− | |||
− | v=semctl(semid, 0, GETVAL); |
||
− | if(v==-1){ |
||
− | perror("semctl1"); |
||
− | exit(1); |
||
− | } |
||
− | printf("val after set: v=%i\n", v); |
||
− | |||
− | if(fork()){ |
||
− | p(semid, 1); |
||
− | wait(&wait_status); |
||
− | } else { |
||
− | p(semid, 2); |
||
− | } |
||
− | |||
− | } |
||
− | |||
− | </nowiki> |