cHam
cHam

Reputation: 2664

in C is it possible to call a function that sleeps without waiting for the sleep to happen?

I have the following code that allocates pages (4KB) of data as char arrays on a Linux system. I am trying to do some testing on how many pages can be created and edited simultaneously under various conditions and this is my current attempt.

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

#define KB(size) ( (size) * 1024 )

void allocatePage(){
 int page = KB(4);
 int i;
 char *p;
 p = (char *)malloc(KB(page));
 memset(p, 'T', KB(page));
 for(i=0;i<10;i++){    // this is the part in question
   memset(p, i, KB(page));
   sleep(3);
 }
}

int main(){
    int p = 2;
    int i;
    int *pages = &p;

    for(i=0;i<250;i++){
      *pages = *pages +1;
      printf("\r%-4d pages allocated",i+1, *pages);
      fflush(stdout);
      allocatePage();
    }
    sleep(10);
    printf("\ndone.\n");

    exit(0);
}

Is there any way to make it so that when I call the allocatePage() function, main will not wait for the for loop to complete? I want to spawn multiple instances and have each one self-modify for a set period of time. Anyone know of a good (or possible) way to do this?

Upvotes: 1

Views: 128

Answers (1)

HAL9000
HAL9000

Reputation: 3751

You can declare your allocatePage function as this:

void *allocatePage(void * data) {
    // do here your stuffs
}

It is already thread-safe, because it only uses local variables. Then, in main, you should change your code as follows:

pthread_t *threadsList[NUMBER_OF_THREADS] = (pthread_t *) malloc(
        sizeof(pthread_t) * NUMBER_OF_THREADS);
for(i=0;i<NUMBER_OF_THREADS;i++){
  *pages = *pages +1;
  printf("\r%-4d pages allocated",i+1, *pages);
  fflush(stdout);
  pthread_create(&threadsList[i], NULL, &allocatePage, (void *) NULL);
}

after that you may want to wait your threads to finish:

for(int i = 0; i < NUMBER_OF_THREADS; i++)
    pthread_join(threadsList[i], NULL);

Here you can find a very good reading about threads in Linux: http://www.advancedlinuxprogramming.com/

Upvotes: 1

Related Questions