Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <sys/time.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <string.h>
- #include <errno.h>
- #include <unistd.h>
- #define WRITE_CHUNK (64*1024*1024)
- void
- show_timeval (const struct timeval *tv)
- {
- printf("%d.%06d\n", (int)tv->tv_sec, (int)tv->tv_usec);
- }
- void
- elapsed_time (struct timeval *t, const struct timeval *a, const struct timeval *b)
- {
- /* insure that a < b */
- if ((a->tv_sec > b->tv_sec) ||
- ((a->tv_sec == b->tv_sec) && (a->tv_usec > b->tv_usec)))
- {
- const struct timeval *tmp;
- tmp = a;
- a = b;
- b = tmp;
- }
- *t = *b;
- t->tv_sec -= a->tv_sec;
- t->tv_usec -= a->tv_usec;
- while (t->tv_usec < 0) {
- t->tv_sec -= 1;
- t->tv_usec += 1000000;
- }
- while (t->tv_usec >= 1000000) {
- t->tv_sec += 1;
- t->tv_usec -= 1000000;
- }
- }
- void *
- writer (void *dummy)
- {
- int fd;
- char *data;
- int i;
- struct timeval start;
- struct timeval end;
- struct timeval diff;
- ssize_t write_ret;
- fd = open("test.dat", O_WRONLY | O_CREAT, 0666);
- if (fd == -1) {
- fprintf(stderr, "Error %d opening file; %s\n", errno, strerror(errno));
- exit(1);
- }
- data = (char *)calloc(WRITE_CHUNK, 1);
- if (data == NULL) {
- fprintf(stderr, "Error allocating memory\n");
- exit(1);
- }
- for (i=0; i<16; i++) {
- if (lseek(fd, 0, SEEK_SET) != 0) {
- fprintf(stderr, "Error %d seeking to start of file; %s\n", errno, strerror(errno));
- exit(1);
- }
- gettimeofday(&start, NULL);
- write_ret = write(fd, data, WRITE_CHUNK);
- if (write_ret != WRITE_CHUNK) {
- fprintf(stderr, "write() returned %d\n", write_ret);
- if (write_ret == -1) {
- fprintf(stderr, "Error is %d; %s\n", errno, strerror(errno));
- }
- exit(1);
- }
- gettimeofday(&end, NULL);
- elapsed_time(&diff, &start, &end);
- printf("%d bytes in %d.%03d seconds\n", write_ret, (int)diff.tv_sec, (int)diff.tv_usec / 1000);
- }
- free(data);
- if (remove("test.dat") != 0) {
- fprintf(stderr, "WARNING: could not remove file, error %d; %s\n", errno, strerror(errno));
- }
- return NULL;
- }
- void *
- happy (void *dummy)
- {
- int cnt;
- for (cnt = 0; ; cnt++) {
- printf("Not blocked... (%d)\n", cnt);
- usleep(200000);
- }
- return NULL;
- }
- int
- main (int argc, char *argv[])
- {
- pthread_t writer_tid;
- pthread_t happy_tid;
- int errnum;
- errnum = pthread_create(&writer_tid, NULL, writer, NULL);
- if (errnum != 0) {
- fprintf(stderr, "pthread_create() failed, error %d\n", errnum);
- return 1;
- }
- errnum = pthread_create(&happy_tid, NULL, happy, NULL);
- if (errnum != 0) {
- fprintf(stderr, "pthread_create() failed, error %d\n", errnum);
- return 1;
- }
- errnum = pthread_join(writer_tid, NULL);
- if (errnum != 0) {
- fprintf(stderr, "pthread_join() failed, error %d\n", errnum);
- return 1;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement