reg3x_mr
reg3x_mr

Reputation: 75

Is there any reason why threads are not executed completely while a C program is running?

I'm practicing with threads in Linux and I'm wondering why the code was written like this:

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


pthread_attr_t attr;

struct thread_info {
    pthread_t   thread_id;
    int         thread_num;
    char        *argv_string;
};

// void *(*__start_routine)(void *)

static void * MyFunction(void *arg){
    int * val;
    val = (int* )arg;
    printf("Thread: %d\n",val);
    //pthread_exit(NULL);
}

int main(void){
    int t=1;
    pthread_t pthread[5];
    
    struct thread_info *tinfo;
    pthread_create(&pthread[0], &attr, MyFunction, (void *)1);
    pthread_create(&pthread[1], &attr, MyFunction, (void *)2);
    //getchar(); // uncoment this line, and 2 thread's will be execute
}

Problem: Rarely, it happens to display two threads at once. Once the getchar() function is uncommented and the code is compiled, two threads are executed. Why?:)

Another thing that makes me wonder, why isn't it written in the documentation that pthread_t is an array?

Linux system, Distribution: Debian Version: glibc 2.37

Upvotes: 0

Views: 34

Answers (0)

Related Questions