glusterfs

Форк
0
83 строки · 1.6 Кб
1
#include <stdio.h>
2
#include <string.h>
3
#include <unistd.h>
4
#include <fcntl.h>
5
#include <pthread.h>
6

7
pthread_t th[5] = {0};
8
void
9
flock_init(struct flock *f, short int type, off_t start, off_t len)
10
{
11
    f->l_type = type;
12
    f->l_start = start;
13
    f->l_len = len;
14
}
15

16
int
17
flock_range_in_steps(int fd, int is_set, short l_type, int start, int end,
18
                     int step)
19
{
20
    int ret = 0;
21
    int i = 0;
22
    struct flock f = {
23
        0,
24
    };
25

26
    for (i = start; i + step < end; i += step) {
27
        flock_init(&f, l_type, i, step);
28
        ret = fcntl(fd, (is_set) ? F_SETLKW : F_GETLK, &f);
29
        if (ret) {
30
            perror("fcntl");
31
            goto out;
32
        }
33
    }
34
out:
35
    return ret;
36
}
37

38
void *
39
random_locker(void *arg)
40
{
41
    int fd = *(int *)arg;
42
    int i = 0;
43
    int is_set = 0;
44

45
    /* use thread id to choose GETLK or SETLK operation*/
46
    is_set = pthread_self() % 2;
47
    (void)flock_range_in_steps(fd, is_set, F_WRLCK, 0, 400, 1);
48

49
    return NULL;
50
}
51

52
int
53
main(int argc, char **argv)
54
{
55
    int fd = -1;
56
    int ret = 1;
57
    int i = 0;
58
    char *fname = NULL;
59

60
    if (argc < 2)
61
        goto out;
62

63
    fname = argv[1];
64
    fd = open(fname, O_RDWR);
65
    if (fd == -1) {
66
        perror("open");
67
        goto out;
68
    }
69

70
    ret = flock_range_in_steps(fd, 1, F_WRLCK, 0, 2000, 2);
71
    for (i = 0; i < 5; i++) {
72
        pthread_create(&th[i], NULL, random_locker, (void *)&fd);
73
    }
74
    ret = flock_range_in_steps(fd, 1, F_WRLCK, 0, 2000, 2);
75
    for (i = 0; i < 5; i++) {
76
        pthread_join(th[i], NULL);
77
    }
78
out:
79
    if (fd != -1)
80
        close(fd);
81

82
    return ret;
83
}
84

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.