Rebecca
Rebecca

Reputation: 21

How to call a function using pthread in c?

How can I call a function in a separate thread using pthreads?

In Java, the answer is as set out here: How to call a method with a separate thread in Java?

How do I do this in C?

Upvotes: 1

Views: 16123

Answers (2)

Daniel Rudy
Daniel Rudy

Reputation: 1439

Technically, you can't...at least not directly.

A thread is an execution path that the processor is following as it runs your program. In today's environment, there are many instances of multiple threads. End-User application software generally has different threads doing different things. On a server however, different threads are doing the same thing which is serving client requests. In any case, each individual thread is running with its own stack frame and processor state.

If you need to pass data off to a different thread to be processed, then there are two ways to do that:

1) Just create a new thread with the data as an argument.

2) Use a work-queue arrangement.

I would use #2 because then you can have multiple producers and consumers running depending on how the queue is setup.

Here's a couple of examples on how to set this up:

https://code.google.com/p/c-pthread-queue/source/browse/trunk/queue.c

http://williams.comp.ncat.edu/comp450/pthreadPC.c

Here's a really good tutorial on pthreads: https://computing.llnl.gov/tutorials/pthreads/

Hope this helps.

Upvotes: 2

anakin
anakin

Reputation: 589

You should first create a function which accepts a void* as an argument and returns a void*. Then make a variable to hold the thread. After that initialize it, and wait to finish work.

Here is a simple code.

#include<stdio.h>
#include<pthread.h>

void* thread_func(void* argument) {
  printf("My first thread!!!\n");
  printf("Passes argument: %d\n", *(int*)argument);
  pthread_exit(NULL); // you could also return NULL here to exit no difference
}

int main() {
  pthread_t my_thread;
  int a = 10;
  pthread_create(&my_thread, NULL, thread_func, &a); // no parentheses here 
  pthread_join(my_thread, NULL);

  return 0;
}

Just be careful with passing pointers, because it can lead to a lot of problems.

If you have more questions please ask.

P.S. I have found this tutorial for multithreading. The only thing that won't compile in c code is the output because the tutorial is written in c++ and uses the iostream library to output.ALL the thread creations, passing arguments, and so on are fully valid in c code. http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm

Upvotes: 2

Related Questions