File: condvar.c

package info (click to toggle)
rtlinux 3.1pre3-2
  • links: PTS
  • area: non-free
  • in suites: sarge, woody
  • size: 4,892 kB
  • ctags: 4,228
  • sloc: ansic: 26,204; sh: 2,069; makefile: 1,414; perl: 855; tcl: 489; asm: 380; cpp: 42
file content (95 lines) | stat: -rw-r--r-- 2,360 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <rtl.h>
#include <time.h>
#include <pthread.h>

static pthread_t thread;
static pthread_mutex_t mutex /* = PTHREAD_MUTEX_INITIALIZER */;
static pthread_cond_t cond;
static int timed=1;
MODULE_PARM(timed,"i");

static void * start_routine(void *arg)
{
	int ret;
	hrtime_t t;
	hrtime_t t2;

	struct sched_param p;
	p . sched_priority = 1;
	pthread_setschedparam (pthread_self(), SCHED_FIFO, &p);

	rtl_printf("RTLinux thread starts on CPU%d\n", rtl_getcpuid());
	if (timed) {
		rtl_printf("RT-thread: about to pthread_cond_timedwait\n");
		t = clock_gethrtime(CLOCK_REALTIME);

		pthread_mutex_lock (&mutex);
		ret = pthread_cond_timedwait (&cond, &mutex, hrt2ts(t + 2000000));
		pthread_mutex_unlock (&mutex);

		t2 = clock_gethrtime(CLOCK_REALTIME);

		rtl_printf("RT-thread: pthread_cond_timedwait returned %d (%d ns elapsed)\n", ret, (unsigned) (t2 - t));
	}


	rtl_printf("RT-thread: about to pthread_cond_wait\n");
	t = clock_gethrtime(CLOCK_REALTIME);

	pthread_mutex_lock (&mutex);
	ret = pthread_cond_wait (&cond, &mutex);
	pthread_mutex_unlock (&mutex);

	t2 = clock_gethrtime(CLOCK_REALTIME);

	rtl_printf("RT-thread: pthread_cond_wait returned %d (%d ns elapsed)\n", ret, (unsigned) (t2 - t));

	return (void *) 35;
}


int init_module(void)
{
	int ret;
	hrtime_t t;
	int sleep = 500000000;
	pthread_attr_t attr;

	rtl_printf("RTLinux condvar test starts on CPU%d\n", rtl_getcpuid());
	pthread_attr_init (&attr);
	/* try to run the thread on another CPU */
	if (rtl_cpu_exists(!rtl_getcpuid())) {
		pthread_attr_setcpu_np(&attr, !rtl_getcpuid());
	}

	pthread_mutex_init (&mutex, NULL);
	pthread_cond_init (&cond, NULL);

	ret = pthread_create (&thread, &attr, start_routine, 0);
	if (ret) {
		rtl_printf("failed to create a thread\n");
		return ret;
	}

	rtl_printf("Linux thread is about to busy-wait for %d ns\n", sleep);
	t = gethrtime();
	while (gethrtime() < t + sleep);

	rtl_printf("Linux thread is about to signal the condition\n");
	pthread_mutex_lock (&mutex);
	ret = pthread_cond_signal (&cond);
	pthread_mutex_unlock (&mutex);
	rtl_printf("Linux thread: pthread_cond_signal returned %d\n", ret);

	return 0;
}


void cleanup_module(void)
{
	void *retval;
	pthread_cancel (thread);
	pthread_join (thread, &retval);
/* 	rtl_printf("RTLinux mutex: joined thread returned %d\n", (int) retval); */
	pthread_mutex_destroy (&mutex);
}