user3461226
user3461226

Reputation:

Pthread arg in C

I am trying to create n threads passing as argument an integer identifier. My problem is that when I read that identifier from the thread shows strange things. This is my code (simplified)

  th_clientes = malloc(sizeof(int) * n_clientes);
  arg_clientes = malloc(sizeof(int) * n_clientes);
  t_espera = malloc(sizeof(int) * n_clientes);

// Create the pthread
  for (cont = 0; cont < n_clientes; ++cont) {
    arg_clientes[cont] = cont;
    pthread_create(&th_clientes[cont],NULL,clientes, &arg_clientes[cont]);
  }

  // Waiting for them.
  for (cont = 0; cont < n_clientes; ++cont) {
    pthread_join(th_clientes[cont],NULL);
  }

void *clientes(void *arg){
  int id = *(int *)arg;

  printf("Cliente %d realizando compra.\n",id);

  t_espera[id] = rand() % MAX;
  sleep(t_espera[id]);

  printf("Cliente %d saliendo del despues de espera %d.\n",id, t_espera[id]);
}

And this is a slice of my output.

Cliente 90 realizando compra.
Cliente 91 realizando compra.
Cliente 92 realizando compra.
Cliente 93 realizando compra.
Cliente 94 realizando compra.
Cliente 15 realizando compra.
Cliente 32551 realizando compra.
Cliente -189507840 realizando compra.
Cliente 32551 realizando compra.
Cliente 32551 saliendo del despues de espera 0.
Violación de segmento (`core' generado)

Thanks.

Upvotes: 2

Views: 119

Answers (1)

Paul R
Paul R

Reputation: 212969

Your are probably not allocating enough memory for your array of pthread_ts. Change:

th_clientes = malloc(sizeof(int) * n_clientes);

to:

th_clientes = malloc(sizeof(pthread_t) * n_clientes);

Upvotes: 2

Related Questions