Es paņēmu šādu demonstrāciju no tīmekļa no 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);
}
Bet, kad es to kompilēju savā datorā (kurā darbojas Ubuntu Linux 9.04), man parādās šāda kļūda:
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
Tas man nav saprotams, jo galvenē ir pthread.h
, kurā jābūt pthread_create
funkcijai. Vai ir kādas idejas, kas notiek nepareizi?
Abas atbildes uz šo jautājumu līdz šim ir nepareizas.
Linux pareizā komanda ir:
gcc -pthread -o term term.c
Kopumā bibliotēkām ir jāseko avotiem un objektiem komandrindā, un -lpthread
nav "opcija", tā ir bibliotēkas specifikācija. Sistēmā, kurā ir instalēta tikai libpthread.a
,
gcc -lpthread ...
neizdosies savienot.