views:

3120

answers:

5

I'm interested in learning to write C programs which use threads. 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?

+9  A: 

It's not the compiler complaining to you, it's the linker. You forgot to link libpthread:

gcc -oterm -lpthread term.c

Also, you forgot to #include <stdlib.h> for a declaration of exit().

Pavel Minaev
+2  A: 

You need to link in the pthread library, by adding giving gcc the -lpthread option:

gcc -lpthread -o term term.c
Jefromi
+3  A: 

Both answers to this question so far are incorrect.
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.

Employed Russian
A: 

what do u mean when you say gcc -lpthread will fail to link?

coz when I use -lpthread to compile the program do what it has to do ...

mariela
A: 

cool,it solve my question,thank you

shindow