Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

341
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda