Home > front end >  How to show parallelism using threads in C?
How to show parallelism using threads in C?

Time:09-28

I'm learning to use threads in C, and i want to make a program that can make 2 things at the same time, I think that's the definition of parallelism. So i create threads with this code:

   pthread_t threads[NUM_THREADS];
   int rc, rc_2;
   int i;
   for( i = 0; i < NUM_THREADS; i   ) {
      printf("main() : creating thread, %d\n", i);
      rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
      rc_2 = pthread_create(&threads[i], NULL, PrintHello_2, (void *)i);
      if (rc || rc_2) {
         printf("Error:unable to create thread, %d\n", rc);
         exit(-1);
      }
   }

And each of those threads call one of these functions:

void *PrintHello(void *threadid) {
   long tid;
   tid = (long)threadid;
   printf("Hello World! Thread ID, %d\n", tid);
   printf("Valores a: %d, b: %d\n", a,b);
   a  = 5;
   pthread_exit(NULL);
}

void *PrintHello_2(void *threadid) {
   long tid;
   tid = (long)threadid;
   printf("Hello World! Thread ID, %d\n", tid);
   printf("Valores a: %d, b: %d\n", a,b);
   b  = 3;
   pthread_exit(NULL);
}

I have 2 global variables a, b, and I just add them 5 and 3 to show how they are changing. But the thing is that I don't understand if this is parallelism..if not how can I see that these two functions or operations are doing their code at the same time? Because when I print the a and b values, it looks like a normal program.

CodePudding user response:

main() exits before the threads have a chance to run for any length of time. pthread_join() will wait for threads to exit in main(). The other problem is that your threads are not particular long-running. This I fixed by running a long loop. Also fixed the issue of int being passed to the thread but read a long.

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

#define NUM_THREADS 2

void *PrintHello(void *threadid) {
    int tid = *(int *) threadid;
    for(int i = 0; i < INT_MAX; i  = tid   1) {
        printf("%d %d\n", tid, i);
    }
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[NUM_THREADS];
    int ids[NUM_THREADS];
    for(int i = 0; i < NUM_THREADS; i   ) {
        ids[i] = i;
        printf("main() : creating thread, %d\n", i);
        int rc = pthread_create(&threads[i], NULL, PrintHello, &ids[i]);
        if (rc) {
            printf("Error:unable to create thread, %d\n", rc);
            exit(-1);
        }
    }
    for(int i = 0; i < NUM_THREADS; i   ) {
        pthread_join(threads[i], 0);
    }
}

and this would print something like this:

1 166
0 265
0 266
1 168
0 267
1 170
1 172
1 174
1 176
1 178
0 268

The output stream must have a mutex otherwise the two threads should generate jumbled output.

  • Related