Back to index

glibc  2.9
tst-cputimer2.c
Go to the documentation of this file.
00001 /* Tests for POSIX timer implementation using thread CPU clock.  */
00002 
00003 #include <unistd.h>
00004 
00005 #if _POSIX_THREADS && defined _POSIX_CPUTIME
00006 
00007 #include <errno.h>
00008 #include <stdio.h>
00009 #include <stdlib.h>
00010 #include <string.h>
00011 #include <fcntl.h>
00012 #include <time.h>
00013 #include <pthread.h>
00014 
00015 static clockid_t worker_thread_clock;
00016 
00017 #define TEST_CLOCK worker_thread_clock
00018 #define TEST_CLOCK_MISSING(clock) \
00019   (setup_test () ? "thread CPU clock timer support" : NULL)
00020 
00021 /* This function is intended to rack up both user and system time.  */
00022 static void *
00023 chew_cpu (void *arg)
00024 {
00025   while (1)
00026     {
00027       static volatile char buf[4096];
00028       for (int i = 0; i < 100; ++i)
00029        for (size_t j = 0; j < sizeof buf; ++j)
00030          buf[j] = 0xaa;
00031       int nullfd = open ("/dev/null", O_WRONLY);
00032       for (int i = 0; i < 100; ++i)
00033        for (size_t j = 0; j < sizeof buf; ++j)
00034          buf[j] = 0xbb;
00035       write (nullfd, (char *) buf, sizeof buf);
00036       close (nullfd);
00037     }
00038 
00039   return NULL;
00040 }
00041 
00042 static int
00043 setup_test (void)
00044 {
00045   /* Test timers on a thread CPU clock by having a worker thread eating
00046      CPU.  First make sure we can make such timers at all.  */
00047 
00048   pthread_t th;
00049   int e = pthread_create (&th, NULL, chew_cpu, NULL);
00050   if (e != 0)
00051     {
00052       printf ("pthread_create: %s\n", strerror (e));
00053       exit (1);
00054     }
00055 
00056   e = pthread_getcpuclockid (th, &worker_thread_clock);
00057   if (e == EPERM || e == ENOENT || e == ENOTSUP)
00058     {
00059       puts ("pthread_getcpuclockid does not support other threads");
00060       return 1;
00061     }
00062   if (e != 0)
00063     {
00064       printf ("pthread_getcpuclockid: %s\n", strerror (e));
00065       exit (1);
00066     }
00067 
00068   timer_t t;
00069   if (timer_create (TEST_CLOCK, NULL, &t) != 0)
00070     {
00071       printf ("timer_create: %m\n");
00072       return 1;
00073     }
00074   timer_delete (t);
00075 
00076   return 0;
00077 }
00078 
00079 #else
00080 # define TEST_CLOCK_MISSING(clock) "process clocks"
00081 #endif
00082 
00083 #include "tst-timer4.c"