Patrick Welche <prlw1@cam.ac.uk>
[netbsd-mini2440.git] / regress / lib / libpthread / preempt1 / preempt1.c
blobeec807f1efa1bb086cd840a3e3aaf4d38f73583c
1 /* $NetBSD: preempt1.c,v 1.2 2003/06/27 13:27:58 skrll Exp $ */
3 #include <assert.h>
4 #include <err.h>
5 #include <fcntl.h>
6 #include <pthread.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <unistd.h>
11 void *threadfunc(void *arg);
13 pthread_mutex_t mutex;
14 pthread_cond_t cond;
15 int started;
17 #define HUGE_BUFFER 1<<20
18 #define NTHREADS 1
20 int
21 main(int argc, char *argv[])
23 int ret, i;
24 pthread_t new;
25 void *joinval;
27 char *mem;
28 int fd;
30 mem = malloc(HUGE_BUFFER);
31 if (mem == NULL)
32 err(1, "malloc");
34 fd = open("/dev/urandom", O_RDONLY, 0);
35 if (fd == -1)
36 err(1, "open");
38 printf("1: preempt test\n");
40 pthread_cond_init(&cond, NULL);
41 pthread_mutex_init(&mutex, NULL);
43 pthread_mutex_lock(&mutex);
45 started = 0;
47 for (i = 0; i < NTHREADS; i++) {
48 ret = pthread_create(&new, NULL, threadfunc, NULL);
49 if (ret != 0)
50 err(1, "pthread_create");
53 while (started < NTHREADS) {
54 pthread_cond_wait(&cond, &mutex);
57 printf("1: Thread has started.\n");
59 pthread_mutex_unlock(&mutex);
60 printf("1: After releasing the mutex.\n");
62 ret = read(fd, mem, HUGE_BUFFER);
63 close(fd);
65 assert(ret == HUGE_BUFFER);
67 ret = pthread_join(new, &joinval);
68 if (ret != 0)
69 err(1, "pthread_join");
71 printf("1: Thread joined.\n");
73 return 0;
76 void *
77 threadfunc(void *arg)
79 printf("2: Second thread.\n");
81 printf("2: Locking mutex\n");
82 pthread_mutex_lock(&mutex);
83 printf("2: Got mutex.\n");
84 started++;
86 pthread_mutex_unlock(&mutex);
87 pthread_cond_signal(&cond);
88 sleep(1);
90 return NULL;