我在C接近pthreads庫,我已經寫下了一些虛擬代碼以便熟悉,但是當我嘗試編譯此代碼時,我得到了一個未定義的對pthread_create的引用,即使我有包括適當的庫和傳遞給函數的參數數量是正確的。你能幫我解決嗎?Pthreads和未定義的參考
我的代碼是:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
void *dummy_thread(void *arg)
{
pthread_exit(NULL);
}
void *dummy_fork(void *arg)
{
exit(0);
}
void pthread_perror(char *string, int errcode)
{
char errmsg[256];
strerror_r(errcode, errmsg, 256);
printf("%s:%s\n", string, errmsg);
}
int main(int argc, char** argv)
{
pthread_t *threads;
int rc, nt, *pids;
long threads_microsecs, fork_microsecs, t;
struct timeval ora, dopo;
float perc;
if (argc != 2)
{
printf("Numero di argomenti %d non valido.\n", argc);
exit(1);
}
nt = strtol(argv[1], NULL, 10);
if (nt < 0)
{
printf("Numero di thread non valido: %d", nt);
exit(1);
}
threads = (pthread_t *) malloc (nt * sizeof(pthread_t));
pids = (int *) malloc (nt * sizeof(int));
if (pids == NULL)
{
perror("malloc");
exit(1);
}
gettimeofday(&ora, NULL);
for (t = 0; t < nt; t++)
{
if (rc = pthread_create(&threads[t], NULL, dummy_thread, NULL))
{
pthread_perror("pthread_create", rc);
exit(1);
}
gettimeofday(&dopo, NULL);
threads_microsecs = dopo.tv_usec - ora.tv_usec;
threads_microsecs += 1000000 * (dopo.tv_sec - ora.tv_sec);
printf("Tempo per la creazione dei thread %ld nsec.\n", threads_microsecs);
gettimeofday(&ora, NULL);
for (t = 0; t < nt; t++)
{
if ((pids[t] = fork()) < 0)
{
perror("fork");
exit(1);
}
if (pids[t] == 0)
{
dummy_fork(NULL);
}
}
gettimeofday(&dopo, NULL);
fork_microsecs = dopo.tv_usec - ora.tv_usec;
fork_microsecs += 1000000 * (dopo.tv_sec - ora.tv_sec);
printf("Tempo per la creazione dei processi %ld nsec", fork_microsecs);
perc = 100 * (((float) fork_microsecs - threads_microsecs)/(float)fork_microsecs);
printf("(%.2f%%)\n", perc);
}
return (EXIT_SUCCESS);
}
許多經驗較少的C程序員似乎需要一點時間才能意識到的一件事是,僅僅包含一個庫頭的include頭部聲明並不能真正滿足鏈接時間依賴關係。 – unwind