Mike John
Mike John

Reputation: 818

Creating a thread and passing a struct to it

I want to create n threads. Then pass them a struct each to populate that struct with data; such as a bool to keep track of whether the thread finished or was interrupted with a terminate signal.

n = 5; // For testing.

pthread_t threads[n];
for(i=0; i<n; i++)
   pthread_create(&threads[i], &thread_structs[i], &functionX);

Assume that thread_structs has been malloced.

Inside the functionX() Notice function doesn't have parameters. Should I make a parameter for the struct? Or where I am passing the struct is okay?

How do I point to the struct that I just passed to the function?

Upvotes: 1

Views: 373

Answers (2)

kfsone
kfsone

Reputation: 24249

That's not how you use pthread_create:

http://man7.org/linux/man-pages/man3/pthread_create.3.html

   int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);

The 3rd argument is your routine, the fourth is an argument that will be forwarded to your routine. Your routine should look like this:

void* functionX(void* voidArg)
{
    thread_struct* arg = (thread_struct*)voidArg;
    ...

and the pthread call should be:

pthread_create(&threads[i], NULL, functionX, &thread_structs[i]);

(unless you have a pthread_attr_t to supply as the second argument).

Upvotes: 5

Paul Draper
Paul Draper

Reputation: 83225

Declare functionX

void* function functionX(void* data) {
}

Then cast data to the whatever the pointer type of &thread_structs[i] is and use it as you please.

Upvotes: 2

Related Questions