The Computer Language
Benchmarks Game

thread-ring C gcc program

source code

/* The Computer Language Benchmarks Game
 * http://benchmarksgame.alioth.debian.org/

* contributed by Premysl Hruby
*/

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <limits.h>

#define THREADS (503)


struct stack {
   char x[PTHREAD_STACK_MIN];
};


/* staticaly initialize mutex[0] mutex */
static pthread_mutex_t mutex[THREADS]; 
static int data[THREADS];
static struct stack stacks[THREADS];
/* stacks must be defined staticaly, or my i386 box run of virtual memory for this
 * process while creating thread +- #400 */

static void* thread(void *num)
{
   int l = (int)num;
   int r = (l+1) % THREADS;
   int token;

   while(1) {
      pthread_mutex_lock(mutex + l);
      token = data[l];
      if (token) {
         data[r] = token - 1;
         pthread_mutex_unlock(mutex + r);
      }
      else {
         printf("%i\n", l+1);
         exit(0);
      }
   }
}



int main(int argc, char **argv)
{
   int i;
   pthread_t cthread;
   pthread_attr_t stack_attr;

   if (argc != 2)
      exit(255);
   data[0] = atoi(argv[1]);

   pthread_attr_init(&stack_attr);
      
   for (i = 0; i < THREADS; i++) {
      pthread_mutex_init(mutex + i, NULL);
      pthread_mutex_lock(mutex + i);

      pthread_attr_setstack(&stack_attr, &stacks[i], sizeof(struct stack)); 
      pthread_create(&cthread, &stack_attr, thread, (void*)i);
   }

   pthread_mutex_unlock(mutex + 0);
   pthread_join(cthread, NULL);   
}
    

notes, command-line, and program output

NOTES:
32-bit Ubuntu one core
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.1) 5.4.0 20160609


Tue, 02 Aug 2016 20:12:39 GMT

MAKE:
/usr/bin/gcc -pipe -Wall -O3 -fomit-frame-pointer -march=native -pthread threadring.c -o threadring.gcc_run 
rm threadring.c
0.11s to complete and log all make actions

COMMAND LINE:
./threadring.gcc_run 50000000

PROGRAM OUTPUT:
292