SAM Example 1
From SoOS
Contents |
[edit] Description
This example shows how to start worker threads.
[edit] Code
#include <stdio.h>
#include <sam.h>
#define N 4
void * worker_routine(void *args)
{
SAM_t sam_context; /* Declare a SAM context variable */
void *myargs; /* Pointer to where the arguments are stored */
/* Start the execution of this worker thread */
/* Extract the SAM context and the arguments */
SAM_Execution_start(args, &sam_context, &myargs);
/* Print the SAM worker ID of this worker thread */
printf("SAM worker id: %d\n", (int)SAM_My_workid(sam_context));
/* Finish the execution of this worker trhead */
SAM_Execution_finish(sam_context);
return NULL;
}
int main(void)
{
SAM_t sam_context; /* Declare a SAM context variable */
SAM_Workerid_t th[N]; /* For storing the worker threads ID's */
void *result; /* Gets the result of the worker thread */
int i;
/* Initialize the SAM context */
SAM_Init(&sam_context);
for(i=0;i<N;i++)
{
/* Create the worker threads running worker_routine */
th[i] = SAM_Execution_create(sam_context, *worker_routine, NULL);
}
for(i=0;i<N;i++)
{
/* Join the worker threads and get the result */
result = (int *)SAM_Execution_join(sam_context, th[i]);
}
/* Destroy the SAM context */
SAM_Destroy(&sam_context);
return 0;
}
[edit] Explanation
This example shows how to start worker threads. In line 38 is the call to function SAM_Execution_create() to create a worker thread. It is called many times to create many worker threads. Later we have to join all of them as shown in line 45 by calling function SAM_Execution_join().
The routine for the worker threads starts in line 6 (the function worker_routine()). The first thing it must do is call SAM_Execution_start() (line 13) to set up correctly the thread and to retrieve the SAM context and the arguments. It must finish by calling SAM_Execution_finish() (line 19) just before returning.
[edit] Compile Command
gcc example1.c -lsam -lpthread -o example1