编译线程程序

时间:2013-12-08 03:33:15

标签: c linux pthreads

我在C中创建了一个使用线程的简单程序。

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>

//Global mutex variable
pthread_mutex_t     mutex = PTHREAD_MUTEX_INITIALIZER;
//Shared variable
int x=100;

//Thread function
void *threadfunc(void *parm)
{
    //Aquire lock
    pthread_mutex_lock(&mutex);
    printf ("Thread has aquire lock!\nIncrementing X by 100. . .\n");
    x+=100;
    printf ("x is %d \n", x);
    pthread_mutex_unlock(&mutex);
    return NULL;
}

//Main function
int main(int argc, char **argv)
{ 
    pthread_t     threadid;
    //creating thread
    pthread_create(&threadid, NULL, threadfunc, (void *) NULL );
    //Aquire lock
    pthread_mutex_lock(&mutex);
    printf ("Main has aquire lock!\ndecrementing X by 100. . .\n");
    x-=100;
    printf ("x is %d \n", x);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
    return 0;
}

当我编译它时,我收到“未定义引用pthread create”的错误。我正在使用此命令进行编译:

gcc -lpthread thread.c -o thr

1 个答案:

答案 0 :(得分:1)

-lpthread 放在<{em> thread.c之后。 gcc正在寻找库方法来满足它在查看库时已经看到的链接要求,所以当你把库放在第一位时,它找不到pthread所需的任何内容并忽略它。