Last active
October 27, 2021 13:10
-
-
Save sitano/f3e88bab492bd42b04411ea81fe86913 to your computer and use it in GitHub Desktop.
testing mmap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <fcntl.h> | |
#include <stdio.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/mman.h> | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
#include <stdbool.h> | |
#include <stdint.h> | |
#include <pthread.h> | |
#define handle_error_en(en, msg) \ | |
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) | |
#define handle_error(msg) \ | |
do { perror(msg); exit(EXIT_FAILURE); } while (0) | |
void errExit(const char *str) { | |
printf("error: %s\n", str); | |
exit(1); | |
} | |
struct task { | |
pthread_t tid; | |
char *addr; | |
off_t size; | |
}; | |
static void * | |
thread_start(void *arg) { | |
struct task *t = arg; | |
size_t x = 0; | |
srand(t->tid); | |
printf("firing at %p+%ld\n", t->addr, t->size); | |
while (1) { | |
off_t off = (rand() % t->size); | |
x += *(t->addr + off); | |
if (rand() % 100 < 1) { | |
t->addr[off] ++; | |
} | |
} | |
return (void *)x; | |
} | |
int | |
main(int argc, char *argv[]) { | |
char *addr, *base; | |
int fd; | |
struct stat sb; | |
const size_t threads = 4; | |
struct task ptt[threads] = {}; | |
if (argc != 2 || strcmp(argv[1], "--help") == 0) | |
errExit("invalid file"); | |
fd = open(argv[1], O_RDONLY); | |
if (fd == -1) | |
errExit("open"); | |
if (fstat(fd, &sb) == -1) | |
errExit("fstat"); | |
base = addr = mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); | |
if (addr == MAP_FAILED) | |
errExit("mmap"); | |
printf("mapped, addr = %p, size = %ld\n", base, sb.st_size); | |
off_t size = 1ll << 29; | |
for (size_t i = 0; i < threads; i ++) { | |
ptt[i].addr = addr + (rand() % (sb.st_size / size)) * size; | |
// ptt[i].addr = addr; | |
ptt[i].size = size; | |
int s = pthread_create(&ptt[i].tid, NULL, &thread_start, &ptt[i]); | |
if (s != 0) | |
handle_error_en(s, "pthread_create"); | |
} | |
printf("started %zu\n", threads); | |
for (int i = 0; i < threads; i++) { | |
void *res; | |
int s = pthread_join(ptt[i].tid, &res); | |
if (s != 0) | |
handle_error_en(s, "pthread_join"); | |
printf("Joined with thread %ld; returned value was %ld\n", ptt[i].tid, (size_t) res); | |
} | |
printf("done\n"); | |
getchar(); | |
exit(EXIT_SUCCESS); | |
return 0; | |
} |
Author
sitano
commented
Oct 26, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment