Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass multiple parameters to a thread function

Tags:

c

unix

posix

ubuntu

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?

like image 838
Searock Avatar asked Jul 15 '26 00:07

Searock


2 Answers

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

like image 199
mmonem Avatar answered Jul 17 '26 15:07

mmonem


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.

like image 42
Johann Gerell Avatar answered Jul 17 '26 14:07

Johann Gerell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!