2 * (c) 2008-2009 Adam Lackorzynski <adam@os.inf.tu-dresden.de>
3 * economic rights: Technische Universität Dresden (Germany)
5 * This file is part of TUD:OS and distributed under the terms of the
6 * GNU General Public License 2.
7 * Please see the COPYING-GPL-2 file for details.
11 * This example uses shared memory between two threads, one producer, one
15 #include <l4/shmc/shmc.h>
17 #include <l4/util/util.h>
21 #include <pthread-l4.h>
23 #include <l4/sys/thread.h>
26 #define CHK(func) if (func) { printf("failure: %d\n", __LINE__); return (void *)-1; }
28 static const char some_data[] = "Hi consumer!";
30 static void *thread_producer(void *d)
34 l4shmc_signal_t s_one, s_done;
35 l4shmc_area_t shmarea;
37 // attach this thread to the shm object
38 CHK(l4shmc_attach("testshm", &shmarea));
41 CHK(l4shmc_add_chunk(&shmarea, "one", 1024, &p_one));
44 CHK(l4shmc_add_signal(&shmarea, "prod", &s_one));
46 CHK(l4shmc_attach_signal_to(&shmarea, "done",
47 pthread_getl4cap(pthread_self()), 10000, &s_done));
49 // connect chunk and signal
50 CHK(l4shmc_connect_chunk_signal(&p_one, &s_one));
52 printf("PRODUCER: ready\n");
56 while (l4shmc_chunk_try_to_take(&p_one))
57 printf("Uh, should not happen!\n"); //l4_thread_yield();
59 memcpy(l4shmc_chunk_ptr(&p_one), some_data, sizeof(some_data));
61 CHK(l4shmc_chunk_ready_sig(&p_one, sizeof(some_data)));
63 printf("PRODUCER: Sent data\n");
65 CHK(l4shmc_wait_signal(&s_done));
73 static void *thread_consume(void *d)
76 l4shmc_area_t shmarea;
78 l4shmc_signal_t s_one, s_done;
80 // attach to shared memory area
81 CHK(l4shmc_attach("testshm", &shmarea));
84 CHK(l4shmc_get_chunk(&shmarea, "one", &p_one));
87 CHK(l4shmc_add_signal(&shmarea, "done", &s_done));
89 // attach signal to this thread
90 CHK(l4shmc_attach_signal_to(&shmarea, "prod",
91 pthread_getl4cap(pthread_self()), 10000, &s_one));
93 // connect chunk and signal
94 CHK(l4shmc_connect_chunk_signal(&p_one, &s_one));
98 CHK(l4shmc_wait_chunk(&p_one));
100 printf("CONSUMER: Received from chunk one: %s\n",
101 (char *)l4shmc_chunk_ptr(&p_one));
102 memset(l4shmc_chunk_ptr(&p_one), 0, l4shmc_chunk_size(&p_one));
104 CHK(l4shmc_chunk_consumed(&p_one));
105 CHK(l4shmc_trigger(&s_done));
116 // create new shared memory area, 8K in size
117 if (l4shmc_create("testshm", 8192))
120 // create two threads, one for producer, one for consumer
121 pthread_create(&one, 0, thread_producer, 0);
122 pthread_create(&two, 0, thread_consume, 0);
124 // now sleep, the two threads are doing the work