2013-12-08 92 views
0

我在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创建”。我使用这个命令编译:

gcc -lpthread thread.c -o thr 
+0

有些系统需要'-pthread'而不是'-lpthread' – RageD

回答

1

-lpthreadthread.c后。 gcc正在寻找库方法来满足它在查看库时已经看到的链接需求,所以当你把库放在第一位时,它不会从pthread中找到任何需要的东西并忽略它。

+0

谢谢@Jherico,它的工作原理。 。 。 :) –