Search code examples
cmultithreadingpthreadshpc

different number of thread is created


I am learning pthread and i am using vs code to run the c code. As per the vs code docs, i installed MSY2S2 MSY and it is installed.

when i run this code:

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

void *bin_finding(void *p){
  int* ptr = (int*)p;
  printf("%d", *ptr);
  // printf("%s", "hello");
}


int main(){
  int data_count = 10;
  int num_of_thread = 4;
  int equalDivisionCount = data_count/num_of_thread;
  int excessCount = data_count%num_of_thread;
  int indexCount[num_of_thread];

  int i;
  pthread_t tid[num_of_thread];
  for(i=0; i<4; i++){
    indexCount[i] = i;
    pthread_create(&tid[i], NULL, bin_finding, &indexCount[i]);
 }
    return 0;
}

when i click run and debug in left most option, it gives different result everytime.

sometime i get 0 sometime 01 sometime 0123

so slmost every run is different and most common is 0.

if anybody, please help me in this.


Solution

  • Your program is exiting before all threads of execution get a chance to finish.

    Use a second loop, after the first, containing calls to pthread_join to wait for each of your threads to fully execute:

    for (int i = 0; i < num_of_thread; i++)
        pthread_join(tid[i], NULL);