在内存映射文件中给计数器+1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <semaphore.h>
#include <stdlib.h>
#include <sys/mman.h>
 
#define SEM_NAME "mysem"
 
const int maxline=4096;
 
int main(int argc, char **argv) {
    int fd, i, nloop, zero=0;
    int *ptr;
    sem_t *mutex;
    char errbuff[maxline];
 
    if(argc!=3) {
        fprintf(stderr, "usage: ./a.out <pathname> <#nloops>\n");
        exit(-1);
    }
 
    nloop=atoi(argv[2]);
 
    fd=open(argv[1], O_RDWR|O_CREAT, 0644);
    if(write(fd, &zero, sizeof(int)) != sizeof(int)) {
        fprintf(stderr, "write error.\n");
        exit(-1);
    }
 
    if((ptr=mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0))==MAP_FAILED) {
        fprintf(stderr, "mmap error.\n");
        exit(-1);
    }
    close(fd);
 
    if((mutex=sem_open(SEM_NAME, O_CREAT|O_EXCL, 0644, 1))==SEM_FAILED) {
        strerror_r(errno, errbuff, maxline);
        fprintf(stderr, "sem_open error: %s\n", errbuff);
        exit(-1);
    }
    sem_unlink(SEM_NAME);
 
    setbuf(stdout, NULL);
 
    if(fork()==0) {
        for(i=0;i<nloop;i++) {
            sem_wait(mutex);
            printf("child: %d\n", (*ptr)++);
            sem_post(mutex);
        }
        exit(0);
    }
 
    for(i=0;i<nloop;i++) {
        sem_wait(mutex);
        printf("parent: %d\n", (*ptr)++);
        sem_post(mutex);
    }
    exit(0);
}

运行结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
$ gcc  incr2.c -pthread
$ ./a.out tmp 5
parent: 0
parent: 1
parent: 2
child: 3
child: 4
child: 5
child: 6
parent: 7
parent: 8
child: 9

  

posted @   东宫得臣  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示