I’m trying to make a simple program in C that will use main thread to print an result, but when I check thread ID when I create thread and when I print result its 2 different IDs. Here is my code:
Cx
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <sys/time.h>
void *Utskrift(void *simpleInt)
{
int simple;
simple = (int)simpleInt;
/*Printing my result and thread id*/
printf(";Hello From Thread ! I got fed with
an int %d! AND it is THREAD ::%d\n",simple,pthread_self());
}
main(){
pthread_t thread_id;
int test=2;
/*Using main thread to print test from method Utskrift*/
pthread_create (&thread_id, NULL,&Utskrift,(void *) test);
/*Taking look at my thread id*/
printf(" (pthread id %d) has started\n", pthread_self());
pthread_join(thread_id,NULL);
}
I’m new to Thread Programming and C as well. So I may have misunderstood pthread_create (&thread_id, NULL,&Utskrift,(void *) test);. Does it use my main thread to call method Utskrift and print the result, or does it create a new thread “child” to my main thread and then the child prints the result? If so, can you please explain for me how to use the main thread to print my “test”.
Output:
(pthread id -1215916352) has started ;Hello From Thread ! I got fed with an int 2! AND it is THREAD ::-1215919248
The
pthread_createfunction(spec) creates a new thread which will execute the function you pass to it (in this caseUtskrift). The value value passed inpthread_create‘s last parameter is passed to the function.If you simply wanted to call the
Utskriftfunction in your main thread, you could do it the normal way:If you want to pass data back from your completed thread to another thread, you can use
pthread_joinwhich will return either the value returned by your thread’s start routine, or the value that thread passes topthread_exit: