glusterfs
83 строки · 1.6 Кб
1#include <stdio.h>2#include <string.h>3#include <unistd.h>4#include <fcntl.h>5#include <pthread.h>6
7pthread_t th[5] = {0};8void
9flock_init(struct flock *f, short int type, off_t start, off_t len)10{
11f->l_type = type;12f->l_start = start;13f->l_len = len;14}
15
16int
17flock_range_in_steps(int fd, int is_set, short l_type, int start, int end,18int step)19{
20int ret = 0;21int i = 0;22struct flock f = {230,24};25
26for (i = start; i + step < end; i += step) {27flock_init(&f, l_type, i, step);28ret = fcntl(fd, (is_set) ? F_SETLKW : F_GETLK, &f);29if (ret) {30perror("fcntl");31goto out;32}33}34out:35return ret;36}
37
38void *39random_locker(void *arg)40{
41int fd = *(int *)arg;42int i = 0;43int is_set = 0;44
45/* use thread id to choose GETLK or SETLK operation*/46is_set = pthread_self() % 2;47(void)flock_range_in_steps(fd, is_set, F_WRLCK, 0, 400, 1);48
49return NULL;50}
51
52int
53main(int argc, char **argv)54{
55int fd = -1;56int ret = 1;57int i = 0;58char *fname = NULL;59
60if (argc < 2)61goto out;62
63fname = argv[1];64fd = open(fname, O_RDWR);65if (fd == -1) {66perror("open");67goto out;68}69
70ret = flock_range_in_steps(fd, 1, F_WRLCK, 0, 2000, 2);71for (i = 0; i < 5; i++) {72pthread_create(&th[i], NULL, random_locker, (void *)&fd);73}74ret = flock_range_in_steps(fd, 1, F_WRLCK, 0, 2000, 2);75for (i = 0; i < 5; i++) {76pthread_join(th[i], NULL);77}78out:79if (fd != -1)80close(fd);81
82return ret;83}
84