File: yield.c

package info (click to toggle)
valgrind 1%3A3.12.0~svn20160714-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 120,428 kB
  • ctags: 70,855
  • sloc: ansic: 674,645; exp: 26,134; xml: 21,574; asm: 7,570; cpp: 7,567; makefile: 7,380; sh: 6,188; perl: 5,855; haskell: 195
file content (87 lines) | stat: -rw-r--r-- 1,799 bytes parent folder | download | duplicates (10)
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
/* 
   Check that a thread which yields with pause (rep;nop) makes less
   progress against a pure spinner.
 */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static pthread_mutex_t m_go = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t c_go = PTHREAD_COND_INITIALIZER;
static pthread_cond_t c_running = PTHREAD_COND_INITIALIZER;

static volatile int alive, running;

static int spin;
static int rep_nop;

static void *spinner(void *v)
{
	pthread_mutex_lock(&m_go);
	while(!alive)
		pthread_cond_wait(&c_go, &m_go);
	running++;
	pthread_cond_signal(&c_running);
	pthread_mutex_unlock(&m_go);

	while(alive)
		spin++;

	return 0;
}

static void *rep_nopper(void *v)
{
	pthread_mutex_lock(&m_go);
	while(!alive)
		pthread_cond_wait(&c_go, &m_go);
	running++;
	pthread_cond_signal(&c_running);
	pthread_mutex_unlock(&m_go);

	while(alive) {
		rep_nop++;
                // This gives a hint to a P4, telling it to pause 
                // (ie. we're in a spin-wait loop)
		asm volatile ("rep; nop" : : : "memory");
	}

	return 0;
}

int main()
{
	pthread_t a, b;

	pthread_create(&a, NULL, spinner, NULL);
	pthread_create(&b, NULL, rep_nopper, NULL);

	/* make sure both threads start at the same time */
	pthread_mutex_lock(&m_go);
	alive = 1;
	pthread_cond_broadcast(&c_go);

	/* make sure they both get started */
	while(running < 2)
		pthread_cond_wait(&c_running, &m_go);
	pthread_mutex_unlock(&m_go);

	sleep(2);

	alive = 0;
	pthread_join(a, NULL);
	pthread_join(b, NULL);

	if (0)
		printf("spin=%d rep_nop=%d rep_nop:spin ratio: %g\n", 
		       spin, rep_nop, (float)rep_nop / spin);

	if (spin > rep_nop)
		printf("PASS\n");
	else
		printf("FAIL spin=%d rep_nop=%d rep_nop:spin ratio: %g\n", 
		       spin, rep_nop, (float)rep_nop / spin);

	return 0;
}