2013-12-08 90 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,它的工作原理。 。 。 :) –