Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

340
Views
My threads are not parallel, they are serial. How to make them parallel?

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);
    }
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!