Pthreads和未定义的引用

时间:2011-07-07 09:20:39

标签: c reference pthreads undefined

我正在接近C中的pthreads库,我已经写下了一些虚拟代码以便熟悉,但是当我尝试编译这段代码时,我得到一个未定义的pthread_create引用,即使我已经包含了正确的库并且传递给函数的参数数量是正确的。你能帮帮我吗?

我的代码是:

#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);
}

2 个答案:

答案 0 :(得分:2)

使用-pthread

编译(错误链接)
gcc -Wall -Wextra -o prog prog.c -pthread

答案 1 :(得分:1)

在eclipse中将“pthread”添加到GCC C链接库。

项目 - &gt;属性 - &gt; C / C ++ Build - &gt;设置 - &gt;工具设置 - &gt; GCC Linker - &gt;图书馆 - &gt;库(-l) - &gt;添加 - &gt; “并行线程”

在此之后构建您的项目。