1 /* spawn - demo of the gras_agent_spawn function */
3 /* The server process wants to compute all prime numbers between 0 and maxint.
4 For that, it spawns amount of child processes and communicate with them
5 through 2 queues (one for the things to do, and another for the things done).
6 Beware, using sockets to speak between main thread and spawned agent
7 is unreliable because they share the same incoming listener thread. */
9 /* Copyright (c) 2010. The SimGrid Team.
10 * All rights reserved. */
12 /* This program is free software; you can redistribute it and/or modify it
13 * under the terms of the license (GNU LGPL) which comes with this package. */
16 #include "xbt/strbuff.h"
18 XBT_LOG_NEW_DEFAULT_CATEGORY(Spawn, "Messages specific to this example");
20 /* defines an interval to be searched */
24 } s_work_chunk_t,*work_chunk_t;
25 xbt_queue_t todo; /* The queue in which the server puts the work to do */
26 xbt_queue_t done; /* the queue in which the workers puts the result of their work; */
28 int worker(int argc, char *argv[]);
29 int worker(int argc, char *argv[]) {
35 xbt_queue_shift_timed(todo,&chunk,0);
37 if (e.category != timeout_error) {
43 break; // Do not break from within the CATCH, exceptions don't like it.
45 INFO2("Got [%d;%d] to do",chunk->min,chunk->max);
46 GRAS_BENCH_ALWAYS_BEGIN();
48 for (i=chunk->min;i<chunk->max;i++) {
51 if (i%j == 0) // not prime: j divides i perfectly
54 if (j==i) // no divisor found: that's prime
55 xbt_dynar_push(chunk->primes,&i);
57 GRAS_BENCH_ALWAYS_END();
58 xbt_queue_push(done,&chunk);
60 INFO0("No more work for me; bailing out");
65 /* ********************************************************************** */
67 /* ********************************************************************** */
68 int server(int argc, char *argv[]);
69 int server(int argc, char *argv[])
78 gras_init(&argc, argv);
80 todo = xbt_queue_new(-1,sizeof(work_chunk_t));
81 done = xbt_queue_new(-1,sizeof(work_chunk_t));
84 INFO0("Prepare some work");
85 for (i=0;i<maxint/perchunk;i++) {
86 chunk = xbt_new0(s_work_chunk_t,1);
87 chunk->min = i*perchunk;
88 chunk->max = (i+1)*perchunk;
89 chunk->primes = xbt_dynar_new(sizeof(int),NULL);
90 xbt_queue_push(todo,&chunk);
93 INFO0("Spawn the kids");
94 for (i = 0; i < child_amount; i++) {
95 worker_args = xbt_new0(char *, 1);
96 worker_args[0] = xbt_strdup("child");
97 worker_args[1] = NULL;
98 gras_agent_spawn(bprintf("child%d",i), NULL, worker, 1, worker_args, NULL);
101 INFO0("Fetch their answers");
102 for (i=0;i<maxint/perchunk;i++) {
104 xbt_strbuff_t buff = xbt_strbuff_new();
108 xbt_queue_pop(done,&chunk);
109 xbt_dynar_foreach(chunk->primes,cursor,data) {
111 sprintf(number,"%d",data);
115 xbt_strbuff_append(buff,",");
116 xbt_strbuff_append(buff,number);
118 INFO3("Primes in [%d,%d]: %s",chunk->min,chunk->max,buff->data);
119 xbt_strbuff_free(buff);
121 xbt_queue_free(&todo);
122 xbt_queue_free(&done);