gpt4 book ai didi

c - 编译时对所有 'sem' 和 'pthread' 函数的 undefined reference

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:11 25 4
gpt4 key购买 nike

<分区>

我正在使用 gcc 编译这个仅依赖于 2 个创建线程的 c 程序,一个用于递增计数器,第二个读取计数器并从计数器中减去一个随机 (0-9) 值,然后显示计数器的值,使用信号量访问它。仍然在编译时我面临很多'对 sem_init/sem_wait/sem_post/pthread_create/..etc 的 undefined reference '我不知道为什么,尽管我在我的程序中将它们关联起来。

我正在使用“gcc -o prog prog.c”来编译我的程序。

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

int counter=0;
int run=1;
sem_t mutex;

void * increm();

void * decrem();


void main()
{ sem_t mutex;
sem_init(&mutex,0,1);
pthread_t t1,t2;
pthread_create(&t1,NULL,increm,NULL);
pthread_create(&t2,NULL,decrem,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
sem_destroy(&mutex);
}
void * increm()
{ while(run)
{sem_wait(&mutex);
counter++;
sem_post(&mutex);
}
pthread_exit(NULL);
}

void * decrem()
{ int i=25;

while(i>0)
{sem_wait(&mutex);
counter-=(rand()%10);
printf("Counter value : %d \n",counter);
i--;
sem_post(&mutex);
}
run=0;
pthread_exit(NULL);
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com