Creating threads for the SPEs

Programs to be run on an SPE are most often written in C or C++ (or assembly language) and can use the SPE data types and intrinsics defined in the SPU C/C++ Language Extensions.

The SPU C/C++ Language Extensions are described in SPU C/C++ language extensions (intrinsics). The SPE code modules must be written and compiled separately from the PPE code modules, using different compilers. A PPE module starts an SPE module running by creating a thread on the SPE, using the spe_context_create, spe_program_load, and spe_context_run library calls, provided in the SPE runtime management library.

The spe_context_create call creates a context for the SPE thread which contains the persistent information about a logical SPE. This information should not be accessed directly by the application. The signature and parameter synopsis for the spe_create_thread library call is:
spe_context_ptr_t  spe_context_create(unsigned int flags, 
  spe_gang_context_ptr_t gang)
Before being able to run an SPE context, an SPE program has to be loaded into the context using the spe_program_load subroutine. The signature and parameter synopsis for the spe_program_load library call is:
int  spe_program_load(spe_context_ptr spe, spe_program_handle_t *program)
An SPE context is executed on a physical SPE by calling the spe_context_run function. This subroutine causes the current PPE thread to transition to a SPE thread by passing its execution control from the PPE to the SPE whose context is scheduled to run on. The PPE resumes execution when the SPE stops.
Note: In order to achieve multiple threads of execution (PPE and SPE threads), separate "pthreads" must be created for each thread of execution using pthread_create. An example is provided in Producing a simple multi-threaded CBE program.
The signature and parameter synopsis for the spe_context_run library call is:
int spe_context_run(spe_context_ptr_t spe, unsigned int *entry, 
  unsigned int runflags, void *argp, void *envp, spe_stop_info_t *stopinfo)
The following code sample shows PPE code creating a SPE context, loading a SPE program into the context and running the program from the current thread.
#include <libspe2.h>
extern spe_program_handle_t spe_code; 
…
spe_context_ptr_t ctx;
unsigned int entry = SPE_DEFAULT_ENTRY;

if ((ctx = spe_context_create(0, NULL)) == NULL) {
	perror(“Failed creating SPE context);
	exit(1);
}
if (spe_program_load(ctx, &spe_code)) {
	perror(“Failed loading program”);
	exit(1);
}
if (spe_context_run(ctx, &entry, 0, NULL, NULL, NULL) < 0) {
	perror(“Failed running context”);
	exit(1);
}