Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Run two functions at the same time?

I have two functions in C:

void function1(){
    // do something
}

void function2(){
    // do something while doing that
}

How would I run these two functions at the exact same time? If possible, please provide an example!

like image 856
Daniel Avatar asked Jun 16 '10 05:06

Daniel


1 Answers

You would use threads.

For example, pthreads is a c library for multithreading.

You can look at this pthreads tutorial for more details.

Here's an example of a program spawning pthreads from this tutorial.

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

Except that (as you probably know) "exact same time" isn't technically possible. Whether you're running on a single or multi-core process, you're at the mercy of the operating system's scheduler to run your threads. There is no guarantee that they will run "at the same time", instead they may time share a single core. You can start two threads and run them concurrently, but that may not be exactly what you're after...

like image 82
Stephen Avatar answered Oct 06 '22 07:10

Stephen