Passing initial arguments to POSIX threads
Only a single argument may be passed to a new thread but,
as that argument is a pointer,
we may pass reference to any amount of data pointed to by that pointer.
In our previous example,
we simply passed the address of a single integer.
In this example we pass the address of a structure,
and each new thread receives its own instance of a structure:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
struct thread_data {
int thread_id;
int sum;
char *message;
};
struct thread_data thread_data_array[NUM_THREADS];
void *hello_world(void *threadarg)
{
struct thread_data *my_data = (struct thread_data *) threadarg;
...
taskid = my_data->thread_id;
sum = my_data->sum;
hello_msg = my_data->message;
...
}
int main(int argc, char *argv[])
{
...
for(long tid=0 ; tid < NUM_THREADS ; tid++) {
thread_data_array[t].thread_id = t;
thread_data_array[t].sum = sum;
thread_data_array[t].message = messages[t];
err = pthread_create(&threads[t], NULL, hello_world, (void *) &thread_data_array[t]);
...
}
}
|
CITS2002 Systems Programming, Lecture 20, p8, 9th October 2023.
|