SAM Example 1

From SoOS

Jump to: navigation, search

Contents

[edit] Description

This example shows how to start worker threads.

[edit] Code

  1. #include <stdio.h>
  2. #include <sam.h>
  3.  
  4. #define N 4
  5.  
  6. void * worker_routine(void *args)
  7. {
  8.   SAM_t sam_context; /* Declare a SAM context variable */
  9.   void *myargs; /* Pointer to where the arguments are stored */
  10.  
  11.   /* Start the execution of this worker thread */
  12.   /* Extract the SAM context and the arguments */
  13.   SAM_Execution_start(args, &sam_context, &myargs);
  14.  
  15.   /* Print the SAM worker ID of this worker thread  */
  16.   printf("SAM worker id: %d\n", (int)SAM_My_workid(sam_context));
  17.  
  18.   /* Finish the execution of this worker trhead */
  19.   SAM_Execution_finish(sam_context);
  20.  
  21.   return NULL;
  22. }
  23.  
  24. int main(void)
  25. {
  26.   SAM_t sam_context; /* Declare a SAM context variable */
  27.   SAM_Workerid_t th[N]; /* For storing the worker threads ID's  */
  28.   void *result; /* Gets the result of the worker thread */
  29.   int i;
  30.  
  31.   /* Initialize the SAM context */
  32.   SAM_Init(&sam_context);
  33.  
  34.  
  35.   for(i=0;i<N;i++)
  36.     {
  37.       /* Create the worker threads running worker_routine  */
  38.       th[i] = SAM_Execution_create(sam_context, *worker_routine, NULL);
  39.     }
  40.  
  41.  
  42.   for(i=0;i<N;i++)
  43.     {
  44.       /* Join the worker threads and get the result */
  45.       result = (int *)SAM_Execution_join(sam_context, th[i]);
  46.     }
  47.  
  48.   /* Destroy the SAM context */
  49.   SAM_Destroy(&sam_context);
  50.  
  51.   return 0;
  52. }

[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

[edit] Download