2

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Searock
  • 6,278
  • 11
  • 62
  • 98

3 Answers3

7

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

mmonem
  • 2,811
  • 2
  • 28
  • 38
3

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.

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122
1

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

RBerteig
  • 41,948
  • 7
  • 88
  • 128
Praveen S
  • 10,355
  • 2
  • 43
  • 69
  • I meant it wont compile if you CTRL-C CTRL-V, However if you use the code and the function calls correctly it will work. Like`memcpy(dest,ptr,size);` and what i have written is enough to understand one has to do as stated here. – Praveen S Sep 09 '10 at 10:33
  • 1
    -1 This is exactly the same way as passing a pointer to a struct except that it's not as type safe and is not as readable. – JeremyP Sep 10 '10 at 15:50
  • @JeremyP - You forgot to add without actually declaring the structure in your comment. I agree with your other points but the OP asked for an alternative. – Praveen S Sep 11 '10 at 06:35
  • @Praveen S: My point is that this isn't really an alternative. It's doing exactly the same thing as passing a struct but without explicitly defining the structure of the block of memory. – JeremyP Sep 12 '10 at 16:37