Skip to content

Instantly share code, notes, and snippets.

@hadrianw
Created April 25, 2018 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadrianw/af20035e77832807da2badfb4eee3f2d to your computer and use it in GitHub Desktop.
Save hadrianw/af20035e77832807da2badfb4eee3f2d to your computer and use it in GitHub Desktop.
Atomic append test.
#if 0
set -e; [ "$0" -nt "$0.bin" ] &&
gcc -Wall -Wextra -pedantic -std=c99 "$0" -o "$0.bin"
exec "$0.bin" "$@"
#endif
#include <stdio.h>
#include <stdlib.h>
#define LEN(x) (sizeof(x)/sizeof((x)[0]))
int
main(int argc, char *argv[])
{
(void)argc;
const int bufsiz = atoi(argv[1]);
const int loops = atoi(argv[2]);
int rc = 0;
int num[24] = {0};
int curr = 0;
int ch, prevch = EOF;
while((ch = getchar()) != EOF) {
if(prevch != EOF && prevch != ch) {
if(curr % bufsiz != 0) {
fprintf(stderr, "%c[%d]\n", prevch, curr);
rc = -1;
}
curr = 0;
}
num[ch - 'a']++;
curr++;
prevch = ch;
}
for(unsigned i = 0; i < LEN(num); i++) {
if(num[i] != loops * bufsiz) {
fprintf(stderr, "%c = %d\n", 'a'+i, num[i]);
rc = -1;
}
}
return rc;
}
#!/bin/sh
set -e
rm -f thefile
./write.c $1 $2 >> thefile
< thefile ./count.c $1 $2
#if 0
set -e; [ "$0" -nt "$0.bin" ] &&
gcc -Wall -Wextra -pedantic -std=c99 -pthread "$0" -o "$0.bin"
exec "$0.bin" "$@"
#endif
#define _XOPEN_SOURCE
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#define LEN(x) (sizeof(x)/sizeof((x)[0]))
static int bufsiz;
static int loops;
void *
writer(void *arg)
{
char id = (intptr_t)arg;
char *buf = malloc(bufsiz);
memset(buf, id, bufsiz);
for(int i = 0; i < loops; i++) {
write(STDOUT_FILENO, buf, bufsiz);
}
free(buf);
return 0;
}
int
main(int argc, char *argv[])
{
(void)argc;
bufsiz = atoi(argv[1]);
loops = atoi(argv[2]);
pthread_t ths[24];
for(unsigned i = 0; i < LEN(ths); i++) {
pthread_create(&ths[i], 0, writer, (void*)(intptr_t)('a'+i));
}
for(unsigned i = 0; i < LEN(ths); i++) {
pthread_join(ths[i], 0);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment