Linux下undefined reference to ‘pthread_create’问题解决

接触了Linux系统编程中的线程编程模块,可gcc pthread.c出现“undefined reference to ‘pthread_create’”,所有关于线程的函数都会有此错误,导致无法编译通过。

问题的原因:pthread不是Linux下的默认的库,也就是在链接的时候,无法找到pthread库中函数的入口地址,于是链接会失败。

解决:在gcc编译的时候,附加要加 -lpthread参数即可解决。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int ticket = 100;
void *route(void *arg)
{
        char *id = (char*)arg;
        while ( 1 ) {
                if ( ticket > 0 ) {
                        usleep(1000);
                        printf("%s sells ticket:%d\n", id, ticket);
                        ticket--;
                } else {
                        break;
                }
        }
}
int main( void )
{
        pthread_t t1, t2, t3, t4;
        pthread_create(&t1, NULL, route, "thread 1");
        pthread_create(&t2, NULL, route, "thread 2");
        pthread_create(&t3, NULL, route, "thread 3");
        pthread_create(&t4, NULL, route, "thread 4");
        pthread_join(t1, NULL);
        pthread_join(t2, NULL);
        pthread_join(t3, NULL);
        pthread_join(t4, NULL);
}

编译链接,显示结果:
这里写图片描述

这是个有缺陷的例子,票数结果会出现负数,所以改进版本如下:

猜你喜欢

转载自blog.csdn.net/fightHHA/article/details/81195168