Searock
Searock

Reputation: 6498

How to pass multiple parameters to a thread function

I have created a function for a thread, but I want to pass multiple parameters to the function.

Here's my source code :

#include "work.h"
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>    // compile with -lpthread

int count = 20;

void* ChildProc(void* arg)
{
    int i;

    for(i = 1; i <= count; i++)
    {   
        printf("%s:%d from thread <%x>\n", arg, i, pthread_self());
        DoWork(i);
    }

    return NULL;
}

void ParentProc(void)
{
    int i;

    for(i = count / 2; i > 0; i--)
    {
        printf("Parent:%d from thread <%x>\n", i, pthread_self());
        DoWork(i);
    }
}

int main(void)
{
    pthread_t child;

    pthread_create(&child, NULL, ChildProc, "Child");

    ParentProc();

    pthread_join(child, NULL); // make child a non-daemon(foreground) thread
}

Now how do I pass multiple parameter to ChildProc() method?

One way is either pass an array or a structure. But what if I want to pass multiple variables without an array or a structure?

Upvotes: 2

Views: 7796

Answers (3)

Johann Gerell
Johann Gerell

Reputation: 25601

One way is either pass a array or a structure.

That's the way. Pointer to a structure, that is.

what if I want to pass multiple variables withous a array or a structure?

Then you're out of luck. Array or a pointer to a structure is what you need.

Upvotes: 3

Praveen S
Praveen S

Reputation: 10393

You can pass a void * buffer stream and if you know the lengths then you can access them. Its similar to implementation of GArrays.

How do you create them?

void *buffer = malloc(sizeofelements);
memcpy(buffer,element1,sizeof element1);
memcpy(buffer+sizeof element1,element2, sizeof element2);

NOTE: The above is not a compilable C code. You need to work on it.

You can use something of the above sort.

You can later access the variables as you already know the size

Upvotes: 1

mmonem
mmonem

Reputation: 2841

A fast and junk answer is to create a struct to hold all parameter and pass its pointer

Upvotes: 7

Related Questions