0

I wrote the skeleton for implementing a C program that calculates the max of an array (w/ a size always a power of 2). It finds the max by creating n/2 threads that each calculate the max of 2 elements in their calcArray[2]. Next, those maxes will again be compared in pairs using the same threads. After each thread is complete, however, it must wait for all other threads to finish before the next comparisons can begin.

These are my questions:

I am having a few issues with this. First, I'm not sure how to dynamically and recursively get calcArray[2]. Next, I'm not sure how to create the threads in the main (where my comment is). Lastly, I need to create my own barrier function which uses binary semaphores to implement the waiting.

Here is what I have so far. I know it is incomplete, I am only providing for context so as to get better answers to the above.

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


struct structMax {
    int max; 
}; 

void *calcThread(calcArray[2], **newNums) {
    for (int counter = 0; counter < ((log(n)/log(2)); counter++ {
        // if active, do work; else jump to barrier right away
        if (calcArray[0] > calcArray[1])
            newNums[counter] = calcArray[0];
        else
            newNums[counter] = calcArray[1];

        // barrier.wait()
        count = count/2; 
        if (count == 1) {
            printf(newNums[0]); 
            break; 
        }
    }

}

int main(){
// Get list of n numbers (each input on individual line) 
  int tmp, nums[3000], calcArray[2], newNums[3000], count;
  int x = 0;
  char line[64];

  /* read at least 63 characters or until newline charater is encountered with */
  /*    fgets(line, sizeof line, stdin) */
  /* if the first character is a newline, then it's an empty line of input */
  int n = 0;
  while ((fgets(line, sizeof line, stdin) != NULL) && (line[0] != '\n'))
    {
      /* parse the read line with sscanf */
      sscanf(line, "%d", &tmp);
      nums[n] = tmp;
      n++;
    }
  printf("Number of items: %d\n", n);
  for(; x < n; x++) {
    printf("%d\n", nums[x]);
  }

  int numThreads = n/2; 
  count = n; 
  calcThread(calcArray[2], newNums);

  // create threads 



  return 0;
}
rsa
  • 69
  • 1
  • 1
  • 6
  • And your question is: why does your code not compile? Assume C&P errors, please edit to correct them. – deamentiaemundi Sep 27 '16 at 18:53
  • remove bracket calcThread(num[idx], num[idx+1], &newNums);, num not declared, should be nums? also provide types void *calcThread(int or (int *) calcArray, int*** newNums) – Anatoly Strashkevich Sep 27 '16 at 18:53
  • My questions are how I would implement the barrier function using semaphores given this code, and how I would create the threads to be passed into the thread function. – rsa Sep 27 '16 at 19:01

0 Answers0