ballballbobo
ballballbobo

Reputation: 61

pthread runs multiple times

I want my each of my threads call multiple functions. How can I achieve that? Right now I have code for threads calling just one function:

pthread_attr_init(&attributes);
if((tid1 = pthread_create(&thread[0],&attributes,produce,NULL)))
{
    printf("\nError in the producer thread\n");
    printf("\n");
}

if((tid2 = pthread_create(&thread[1],&attributes,consume,NULL)))
{
    printf("\nERror in the consumer thread\n");
}

pthread_join(thread[0],NULL);
pthread_join(thread[1],NULL);

Would calling pthread_create spawn two new threads?

Upvotes: 0

Views: 1489

Answers (1)

P.P
P.P

Reputation: 121357

You can't "pass" multiple functions to pthread_create(). There's simply no provision for that. However, you can call whatever functions you want in the thread function, just like any other function call.

void *produce(void *arg)
{
   func1();
   func2();
   ...
}

void *consume(void *arg)
{
   funcx();
   funcy();
   ...
}

int main(void) 
{
...

if((tid1 = pthread_create(&thread[0],&attributes,produce,NULL)))
{
    printf("\nError in the producer thread\n");
    printf("\n");
}

if((tid2 = pthread_create(&thread[1],&attributes,consume,NULL)))
{
    printf("\nERror in the consumer thread\n");
}
...
}

Or if what you wanted was separate threads for each of those (e.g. func1 and func2 in the sample) functions to be separate threads, then you just need to call pthread_create() as many times with each of these functions as an argument (i.e. thread function).

Upvotes: 1

Related Questions