I picked up the following demo off the web from https://computing.llnl.gov/tutorials/pthreads/
#include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { long tid; tid = (long)threadid; printf("Hello World! It's me, thread #%ld!\n", tid); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc; long t; for(t=0; t<NUM_THREADS; t++){ printf("In main: creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } pthread_exit(NULL); }
But when I compile it on my machine (running Ubuntu Linux 9.04) I get the following error:
corey@ubuntu:~/demo$ gcc -o term term.c term.c: In function ‘main’: term.c:23: warning: incompatible implicit declaration of built-in function ‘exit’ /tmp/cc8BMzwx.o: In function `main': term.c:(.text+0x82): undefined reference to `pthread_create' collect2: ld returned 1 exit status
This doesn't make any sense to me, because the header includes pthread.h
, which should have the pthread_create
function. Any ideas what's going wrong?
You are getting the reference error to pthread_create due to several reasons such as the pthread header file is missing, you are compiling a C program with GCC on Linux, and you are using the wrong compiler flag, or pthread is missing from your Integrated Development Environment.
On linux, pthread functions live in the libpthread library. So you have to link to that. The proper way, when using pthreads, is to compile and link using the -pthread , which, among other things, will link in the pthread library.
The pthread_create() function will fail if: [EAGAIN] The system lacked the necessary resources to create another thread, or the system-imposed limit on the total number of threads in a process PTHREAD_THREADS_MAX would be exceeded.
If pthread_create() completes successfully, thread will contain the ID of the created thread. If it fails, no new thread is created, and the contents of the location referenced by thread are undefined. System default for the thread limit in a process is set by MAXTHREADS in the BPXPRMxx parmlib member.
For Linux the correct command is:
gcc -pthread -o term term.c
In general, libraries should follow sources and objects on command line, and -lpthread
is not an "option", it's a library specification. On a system with only libpthread.a
installed,
gcc -lpthread ...
will fail to link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With