天天看點

線程異常:undefined reference to 'pthread_create' 處理

源碼:

#include <stdio.h>

#include <pthread.h>

#include <sched.h>

void *producter_f (void *arg);

void *consumer_f (void *arg);

int buffer_has_item=0;

pthread_mutex_t mutex;

int running =1 ;

int main (void)

{

pthread_t consumer_t;

pthread_t producter_t;

pthread_mutex_init (&mutex,null);

pthread_create(&producter_t, null,(void*)producter_f, null );

pthread_create(&consumer_t, null, (void *)consumer_f, null);

usleep(1);

running =0;

pthread_join(consumer_t,null);

pthread_join(producter_t,null);

pthread_mutex_destroy(&mutex);

return 0;

}

void *producter_f (void *arg)

while(running)

pthread_mutex_lock (&mutex);

buffer_has_item++;

printf("生産,總數量:%d\n",buffer_has_item);

pthread_mutex_unlock(&mutex);

void *consumer_f(void *arg)

pthread_mutex_lock(&mutex);

buffer_has_item--;

printf("消費,總數量:%d\n",buffer_has_item);

錯誤場景:

[root@luozhonghua 04]# gcc -o mutex ex04-5-mutex.c

/tmp/cczufiqr.o: in function `main':

ex04-5-mutex.c:(.text+0x3d): undefined reference to `pthread_create'

ex04-5-mutex.c:(.text+0x61): undefined reference to `pthread_create'

ex04-5-mutex.c:(.text+0x8b): undefined reference to `pthread_join'

ex04-5-mutex.c:(.text+0x9f): undefined reference to `pthread_join'

collect2: ld returned 1 exit status

分析:pthread 庫不是 linux 系統預設的庫,連接配接時需要使用靜态庫 libpthread.a

處理:

在編譯中加 -lpthread 參數

[root@luozhonghua 04]# gcc -lpthread -o mutex ex04-5-mutex.c

繼續閱讀