zoukankan      html  css  js  c++  java
  • 线程异常: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 ",buffer_has_item);
    pthread_mutex_unlock(&mutex);
    }
    }


    void *consumer_f(void *arg)
    {
    while(running)
    {
    pthread_mutex_lock(&mutex);
    buffer_has_item--;
    printf("消费,总数量:%d ",buffer_has_item);
    pthread_mutex_unlock(&mutex);
    }
    }



    错误场景:

    [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



  • 相关阅读:
    反转链表 16
    CodeForces 701A Cards
    hdu 1087 Super Jumping! Jumping! Jumping!(动态规划)
    hdu 1241 Oil Deposits(水一发,自我的DFS)
    CodeForces 703B(容斥定理)
    poj 1067 取石子游戏(威佐夫博奕(Wythoff Game))
    ACM 马拦过河卒(动态规划)
    hdu 1005 Number Sequence
    51nod 1170 1770 数数字(数学技巧)
    hdu 2160 母猪的故事(睡前随机水一发)(斐波那契数列)
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4045608.html
Copyright © 2011-2022 走看看