(CFLAGS-tst-align.c): Add -mpreferred-stack-boundary=4.
[glibc.git] / linuxthreads / Examples / ex18.c
blob283396bede25a20ad3576f59e8aeb41a702c5ac2
1 /*
2 * Beat up the pthread_key_create and pthread_key_delete
3 * functions.
4 */
6 #if 0
7 #define CHATTY
8 #endif
10 #include <stdio.h>
11 #include <errno.h>
12 #include <stdlib.h>
13 #include <pthread.h>
14 #include <unistd.h>
16 const int beatup_iterations = 10000;
17 const int num_threads = 30;
18 const int max_keys = 500;
20 struct key_list {
21 struct key_list *next;
22 pthread_key_t key;
25 struct key_list *key_list;
26 pthread_mutex_t key_lock = PTHREAD_MUTEX_INITIALIZER;
29 * Create a new key and put it at the tail of a linked list.
30 * If the linked list grows to a certain length, delete a key from the
31 * head of * the list.
34 static void
35 beat_up(void)
37 struct key_list *new = malloc(sizeof *new);
38 struct key_list **iter, *old_key = 0;
39 int key_count = 0;
41 if (new == 0) {
42 fprintf(stderr, "malloc failed\n");
43 abort();
46 new->next = 0;
48 if (pthread_key_create(&new->key, 0) != 0) {
49 fprintf(stderr, "pthread_key_create failed\n");
50 abort();
53 if (pthread_getspecific(new->key) != 0) {
54 fprintf(stderr, "new pthread_key_t resolves to non-null value\n");
55 abort();
58 pthread_setspecific(new->key, (void *) 1);
60 #ifdef CHATTY
61 printf("created key\n");
62 #endif
64 pthread_mutex_lock(&key_lock);
66 for (iter = &key_list; *iter != 0; iter = &(*iter)->next)
67 key_count++;
69 *iter = new;
71 if (key_count > max_keys) {
72 old_key = key_list;
73 key_list = key_list->next;
76 pthread_mutex_unlock(&key_lock);
78 if (old_key != 0) {
79 #ifdef CHATTY
80 printf("deleting key\n");
81 #endif
82 pthread_key_delete(old_key->key);
86 static void *
87 thread(void *arg)
89 int i;
90 for (i = 0; i < beatup_iterations; i++)
91 beat_up();
92 return 0;
95 int
96 main(void)
98 int i;
99 pthread_attr_t detached_thread;
101 pthread_attr_init(&detached_thread);
102 pthread_attr_setdetachstate(&detached_thread, PTHREAD_CREATE_DETACHED);
104 for (i = 0; i < num_threads; i++) {
105 pthread_t thread_id;
106 while (pthread_create(&thread_id, &detached_thread, thread, 0) == EAGAIN) {
107 /* let some threads die, so system can breathe. :) */
108 sleep(1);
112 pthread_exit(0);