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

实验环境

Centos 7.0, gcc 4.8.5

问题

在运行一个多线程的c文件时候报了错:
这里写图片描述


#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

void* thread1(void*);
void* thread2(void*);
void* thread3(void*);

int i=1;
int buffer1[1];//char buffer1[4];
int buffer2[1];

sem_t sample_sem;


int main(void)
{
    pthread_t t1;
    pthread_t t2;
    pthread_t t3;

    pthread_create(&t1,NULL,(void*)thread1,NULL);
    pthread_create(&t2,NULL,(void*)thread2,NULL);
    pthread_create(&t3,NULL,(void*)thread3,NULL);

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_join(t3,NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    exit(0);

}

void* thread1(void* arg)
{
    FILE *f1;
    if((f1=(fopen("1.dat","r"))) == NULL){
        printf("Open 1.dat failed.");
    }

    for(i=1;i<=27;i++)
    {
        pthread_mutex_lock(&mutex);

        if ((i%2==0) || (i%3==0)){
            pthread_cond_signal(&cond);
        }
        else{
            printf("thread1's i : %d\n",i);
            fscanf(f1,"%d",buffer1);//fread(buffer1,2,1,f1);
            printf("thread1 write: %d\n", buffer1[0]);
        }
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    fclose(f1);
}

void* thread2(void* arg)
{
    FILE *f2;
    if((f2=(fopen("2.dat","r"))) == NULL){
        printf("Open 2.dat failed.");
    }

    while(i<=27){
        sem_post(&sample_sem); 
        pthread_mutex_lock(&mutex);

        if (i%2!=0){
            pthread_cond_wait(&cond,&mutex);
        }

        printf("thread2's i : %d\n",i);
        fscanf(f2,"%d",buffer2);//fread(buffer1,2,1,f1);
        printf("thread2 write: %d\n", buffer2[0]);


        pthread_mutex_unlock(&mutex);
        sleep(1);
    }

    fclose(f2);
}

void* thread3(void* arg)
{
    while(i<=27)
    {
        sem_wait(&sample_sem); 
        pthread_mutex_lock(&mutex);

        if (i%3!=0){
            pthread_cond_wait(&cond,&mutex);
        }

        printf("thread3's i:%d\n",i);
        printf("PLUS: %d + %d = %d\n",buffer1[0],buffer2[0],buffer1[0]+buffer2[0]);
        printf("MULTIPLY: %d * %d = %d\n",buffer1[0],buffer2[0],buffer1[0]*buffer2[0]);
        //printf("get B1: %d,",buffer1[0]);
        //printf("get B2: %d\n",buffer2[0]);


        pthread_mutex_unlock(&mutex);
        sleep(1);

    }
}

PS:这个代码有问题- -运行完了退不出来。。。好迷啊


原因

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


解决

在gcc编译的时候,附加要加 -lpthread参数即可解决。
这里写图片描述

  • 11
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值