Jono
Jono

Reputation: 223

C thread argument

Basic function of my program: create number of counters (0), create number of instructions per threads, create the struct instructions which contain counter*, repetitions and work_fn (increment, decrement etc). Program will build all the dynamic structure (already coded up) then spawn threads and join. One thread can have more than one instructions.

static void* worker_thread(void *arg){
  long long *n;
  pthread_mutex_lock( &lock1 );

  n = (long long *) arg;
  printf("Testing: %lld.\n", n);

  pthread_mutex_unlock( &lock1 );

  return NULL;
}

//nthreads is the total number of threads

for(int i=0; i < nthreads ; i++){
  pthread_create( &thread_id[i], NULL, worker_thread, &i); //Problem
}


for(int i=0; i < nthreads ; i++){
  pthread_join( thread_id[i], NULL);
}

I am trying to test the thread function, firstly create number of threads then join them. But I can't seems to pass the current thread number [i] in my case to the worker thread function.

Upvotes: 0

Views: 986

Answers (2)

user703016
user703016

Reputation: 37995

int n = (int)arg;

In your worker_thread function.

And

(void*)i

Instead of &i in your thread spawn

Upvotes: 1

Igor
Igor

Reputation: 1486

Use

(void *) i

in pthread_create

and then

int i = (int) arg

Upvotes: 2

Related Questions