0

I'm trying to force my program to sleep for a second after it creates a thread. I can make the thread sleep within its process but not in the main. Everything I read says it is just a system process that should work wherever it's called. I want it to sleep after printing that the thread has been created (before the join). There is no delay between the "create" and "joined and exited" print statements. Can you tell why it isn't working?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define SECONDS   1     //seconds to sleep
#define SIZE     25     //number of fibonaccis to be computed

int *fibResults;        //array to store fibonacci results
int  idx;               //index for the threads

//executes and exits each thread
void *run(void *param) {
  if (idx == 0) {

    sleep(SECONDS);
    fibResults[idx] = 0;
    pthread_exit(0);

  } else if (idx == 1) {

    sleep(SECONDS);   
    fibResults[idx] = 1;
    pthread_exit(0);   

  } else {

    sleep(SECONDS);
    fibResults[idx] = fibResults[idx -1] + fibResults[idx -2];
    pthread_exit(0);

  }
}


int main(void) {
  fibResults = malloc(SIZE * sizeof(*fibResults));
  pthread_attr_t attrs;
  pthread_attr_init(&attrs);

  for (idx = 0; idx < SIZE; idx++) {
    pthread_t thread;
    pthread_create(&thread, &attrs, run, NULL);

    printf("Thread[%d] created\t", idx);

    sleep(SECONDS); //THIS IS WHERE SLEEP ISN'T WORKING!!!!!!!!!!!!!

    pthread_join(thread, NULL);

    printf("Thread[%d] joined & exited\t", idx);
    printf("The fibonacci of %d= %d\n", idx, fibResults[idx]);
  }
  return 0;
}
efuddy
  • 95
  • 1
  • 8

1 Answers1

0
for (idx = 0; idx < SIZE; idx++)
{
  pthread_t thread;
  pthread_create(&thread, &a, run, NULL);
  printf("Thread[%d] created\t", idx);
  fflush(stdout);
  sleep(SECONDS);
  pthread_join(thread, NULL);
  printf("Thread[%d] joined & exited\t", idx);
  printf("The fibonacci of %d= %d\n", idx, fibResults[idx]);
}
John Kugelman
  • 307,513
  • 65
  • 473
  • 519
efuddy
  • 95
  • 1
  • 8