How to correctly receive an argument by creating a thread

Asked

Viewed 40 times

0

I’m trying to create a thread to wait a while and then create a second thread using:

pthread_create(&thread_intermedia, NULL, criar_thread, &init);

where init is an integer, let’s say it is 100. The function creat_thread is as follows:

void * criar_thread(void * t){
    time_t t_atual = (time(NULL) - t_inicial) * 1000;   //em milissegundos
    long init = *((long*)t);   

    long tempo_espera = (init * unidade_tempo) - t_atual;   //em milissegundos
    printf("Vou esperar %ld milissegundos para criar a thread\n", tempo_espera);

    usleep(tempo_espera / 1000);
    //pthread_create()
    printf("Thread criada\n");
    pthread_exit(NULL);
}

my problem here is getting the value of init.

long init = *((long*)t);

This does not seem to be working properly, it always prints huge numbers when it should print a number on the order of hundreds/thousands. Any suggestions?

1 answer

1


long init = (long)*((int*)t);

  1. converts (void *)t to (int *)t, an integer pointer.
  2. you access the value to which the integer pointer points with *(int *)t.
  3. and convert the integer to long with one last Typecast: (long)*(int *)t

Browser other questions tagged

You are not signed in. Login or sign up in order to post.