1 year ago

#389018

test-img

Mr Digs

Not getting output from function called by pthreads

I am trying to learn pthreads as part of my C module for university. I have created a small bit of code to just verify that the pthreads are being created and it returning some data. Please ignore all comments in the program. They are random notes to remind me of things.

This program compiles. But does not produce any output (in this case tid & i). what I am expecting, is that when I throw it a command line argument. It is used for number of threads.

see below for the code:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//struct

    struct threadArgs{
    int start;
    int finish;
};

// first part - create a function that takes two arguments. 

void *threadMain(void *p){
int i,c;
struct threadArgs *pargs = p;
// variables here for leibniz
int nstart=pargs->start, nfinish=pargs->finish; 
pthread_t tid = pthread_self(); //The pthread_self() function returns the ID of the calling thread

// i++ is slower than ++i. The difference is in order of operations. i++ copies and increases then throws away. ++i returns the value, and then increments it.
for(i=nstart; i<=nfinish; i++)
  { 
    for(c=2; c<=i-1; c++)
    {
      if ( i%c==0 )
        break;
    }
    if ( c==i )
      printf("Thread %ld : %d\n",tid, i);
  }
  return 0;
}

int main(int argc, char **argv){
  int numThreads = 0;
  int i;
  pthread_t thrID[100];
  struct threadArgs targs[100];

  if ( argc > 1 ) {
    numThreads = atoi(argv[1]); 
  }
  if (numThreads > 0 && numThreads <= 100){
    int chunksize = 10000/numThreads ;
    for (i=0; i < numThreads; i++){
      targs[i].start = i * chunksize;
      targs[i].finish = (i * chunksize) + chunksize;
      pthread_create(&thrID[i], NULL, threadMain, &targs[i]);
    }
    for (i=0; i < numThreads; i++){
      pthread_join(thrID[i], NULL);
    }
  }
}

The output seen from this... well there isn't one. The program just finishes.

Thank you.

c

pthreads

0 Answers

Your Answer

Accepted video resources