I am practicing multi-threading.
I create two posix threads that display a text to the screen (infinite loop), but it seem only the first thread run. I modify the program without looping, first thread prints, following is second thread. It seems that my thread are not parallel, first thread has to finish before thread two start. How can I make them parallel?
Thanks,
hdr.h
#ifndef HDR_HDR_H_
#define HDR_HDR_H_
#define HDR_HDR_H_
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#endif /* HDR_HDR_H_ */
multithread01.c
#include "../hdr/myfunc.h"
pthread_mutex_t lock;
int main(int argc, char **argv)
{
pthread_t tid01;
pthread_t tid02;
void * status01;
void * status02;
pthread_create(&tid01, NULL, PrintOut01(), NULL);
pthread_create(&tid02, NULL, PrintOut02(), NULL);
pthread_join(&tid01, &status01);
pthread_join(&tid02, &status02);
return 0;
}
myfunc.h
#ifndef HDR_MYFUNC_H_
#define HDR_MYFUNC_H_
#include "../hdr/hdr.h"
void * PrintOut01 (void);
void * PrintOut02 (void);
#endif /* HDR_MYFUNC_H_ */
myfunc.c
#include "../hdr/hdr.h"
extern pthread_mutex_t lock;
void * PrintOut01 ()
{
while (1)
{
pthread_mutex_lock(&lock);
printf ("This is thread 01\n");
pthread_mutex_unlock(&lock);
}
}
void * PrintOut02 ()
{
while (1)
{
pthread_mutex_lock(&lock);
printf ("This is thread 02\n");
pthread_mutex_unlock(&lock);
}
}
It's because you are calling the functions in your pthread_create call, you're not passing the function pointers.
Compare the incorrect
pthread_create(&tid01, NULL, PrintOut01(), NULL);
with the correct
pthread_create(&tid01, NULL, PrintOut01, NULL);
If you remove the loops in the functions, and create the threads like you do in the code in the question, then the pthread_create will use whatever you return from the functions as the pointer to the thread function, and unless you return a pointer to a function you will have undefined behavior.