1 #include <ccan/io/io.h>
2 #include <ccan/time/time.h>
11 #define NUM_ITERS 10000
15 struct io_conn *reader, *writer;
19 static struct io_op *poke_writer(struct io_conn *conn, struct buffer *buf);
20 static struct io_op *poke_reader(struct io_conn *conn, struct buffer *buf);
22 static struct io_op *do_read(struct io_conn *conn, struct buffer *buf)
24 assert(conn == buf->reader);
26 return io_read(&buf->buf, sizeof(buf->buf),
27 io_next(conn, poke_writer, buf));
30 static struct io_op *do_write(struct io_conn *conn, struct buffer *buf)
32 assert(conn == buf->writer);
34 return io_write(&buf->buf, sizeof(buf->buf),
35 io_next(conn, poke_reader, buf));
38 static struct io_op *poke_writer(struct io_conn *conn, struct buffer *buf)
40 assert(conn == buf->reader);
42 if (buf->iters == NUM_ITERS)
43 return io_close(conn, NULL);
46 io_wake(buf->writer, do_write, buf);
48 /* I'll wait until you wake me. */
52 static struct io_op *poke_reader(struct io_conn *conn, struct buffer *buf)
54 assert(conn == buf->writer);
56 io_wake(buf->reader, do_read, buf);
58 if (++buf->iters == NUM_ITERS)
59 return io_close(conn, NULL);
61 /* I'll wait until you tell me to write. */
65 static struct io_op *reader(struct io_conn *conn, struct buffer *buf)
67 assert(conn == buf->reader);
69 /* Wait for writer to tell us to read. */
76 int fds[2], last_read, last_write;
77 struct timespec start, end;
78 struct buffer buf[NUM];
85 for (i = 1; i < NUM; i++) {
89 memset(buf[i].buf, i, sizeof(buf[i].buf));
90 sprintf(buf[i].buf, "%i-%i", i, i);
92 buf[i].reader = io_new_conn(last_read, reader, NULL, &buf[i]);
94 err(1, "Creating reader %i", i);
95 buf[i].writer = io_new_conn(fds[1], do_write, NULL, &buf[i]);
97 err(1, "Creating writer %i", i);
101 /* Last one completes the cirle. */
104 sprintf(buf[i].buf, "%i-%i", i, i);
105 buf[i].reader = io_new_conn(last_read, reader, NULL, &buf[i]);
107 err(1, "Creating reader %i", i);
108 buf[i].writer = io_new_conn(last_write, do_write, NULL, &buf[i]);
110 err(1, "Creating writer %i", i);
112 /* They should eventually exit */
114 if (io_loop() != NULL)
118 for (i = 0; i < NUM; i++) {
119 char b[sizeof(buf[0].buf)];
120 memset(b, i, sizeof(b));
121 sprintf(b, "%i-%i", i, i);
122 if (memcmp(b, buf[(i + NUM_ITERS) % NUM].buf, sizeof(b)) != 0)
123 errx(1, "Buffer for %i was '%s' not '%s'",
124 i, buf[(i + NUM_ITERS) % NUM].buf, b);
127 printf("run-many: %u %u iterations: %llu usec\n",
128 NUM, NUM_ITERS, (long long)time_to_usec(time_sub(end, start)));