
#include <libspe.h>
#include <stdio.h>
#include <stddef.h>

#define NUM_SPE 4

spe_program_handle_t *spe_prog;

struct spe_data
{
	long last_data;
};

void handle_event(struct spe_data *spe, struct spe_event *event)
{
	printf(">> %ld\n", spe->last_data);
	//spe->last_data = event->data;
}

int main(int argc, char **argv)
{
	speid_t speid[NUM_SPE];
	spe_gid_t spe_gid;
	struct spe_data spe_data[NUM_SPE];
	int done;
	int i;

	spe_prog = spe_open_image("spe_prog");
	
	spe_gid = spe_create_group(0, 0, 1);
	for (i = 0; i < NUM_SPE; i++) {
		speid[i] = spe_create_thread(spe_gid, spe_prog, NULL, NULL, 0xffff, 0);
		/* set application data. */
		spe_data[i].last_data = i;
		spe_set_app_data(speid[i], &spe_data[i]);
	}

	done = 0;
	while (done < NUM_SPE) {
		struct spe_event event;
		struct spe_data *cur_spe;
    
		event.gid = spe_gid;
		event.events = SPE_EVENT_MAILBOX | SPE_EVENT_THREAD_EXIT;
		spe_get_event(&event, 1, -1);
    
		switch (event.revents) {
			case SPE_EVENT_MAILBOX:
				/* get application data and handle the event. */
			 	spe_get_app_data(event.speid, (void **)&cur_spe);
      				handle_event(cur_spe, &event);
				break;
			case SPE_EVENT_THREAD_EXIT:
			 	spe_get_app_data(event.speid, (void **)&cur_spe);
      				handle_event(cur_spe, &event);
				done++;
      				break;
		}
 	}
}
