linux 中对 pthread_create 的未定义引用(c 编程)
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t e,n,s;
int a[10];
int flag=0;
int sizeb=10;
void take()
{
int out;
if(flag==0)
{
printf("the consumer is waiting\n");
}
else
{
printf("\n the consumer has entered the cs:\n");
for(out=0;out<10;out++)
{
printf("\t%d",a[out]);
}
}
}
void consumer()
{
sem_wait(&n);
sem_wait(&s);
printf("\n Consumer Unit\n");
take();
if(flag==1)
{
printf("\n the consumer has consumed\n");
}
sem_post(&s);
sem_post(&e);
}
void append()
{
int in;
printf("\n the producer has entered the cs\n");
for(in=0;in<10;in++)
{
a[in]=in+1;
printf("\t%d",a[in]);
}
}
void producer()
{
sem_wait(&e);
sem_wait(&s);
printf("\n producer unit\n");
append();
printf("\n the producer has produced\n");
sem_post(&s);
sem_post(&n);
flag=1;
}
int main()
{
sem_init(&s,0,1);
sem_init(&n,0,1);
sem_init(&e,0,20);
pthread_t p1,p2,p3;
pthread_create(&p1,NULL,(void *)consumer,NULL);
pthread_join(p1,NULL);
pthread_create(&p2,NULL,(void *)producer,NULL);
pthread_join(p2,NULL);
pthread_create(&p3,NULL,(void *)consumer,NULL);
pthread_join(p3,NULL);
return 0;
}
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t e,n,s;
int a[10];
int flag=0;
int sizeb=10;
void take()
{
int out;
if(flag==0)
{
printf("the consumer is waiting\n");
}
else
{
printf("\n the consumer has entered the cs:\n");
for(out=0;out<10;out++)
{
printf("\t%d",a[out]);
}
}
}
void consumer()
{
sem_wait(&n);
sem_wait(&s);
printf("\n Consumer Unit\n");
take();
if(flag==1)
{
printf("\n the consumer has consumed\n");
}
sem_post(&s);
sem_post(&e);
}
void append()
{
int in;
printf("\n the producer has entered the cs\n");
for(in=0;in<10;in++)
{
a[in]=in+1;
printf("\t%d",a[in]);
}
}
void producer()
{
sem_wait(&e);
sem_wait(&s);
printf("\n producer unit\n");
append();
printf("\n the producer has produced\n");
sem_post(&s);
sem_post(&n);
flag=1;
}
int main()
{
sem_init(&s,0,1);
sem_init(&n,0,1);
sem_init(&e,0,20);
pthread_t p1,p2,p3;
pthread_create(&p1,NULL,(void *)consumer,NULL);
pthread_join(p1,NULL);
pthread_create(&p2,NULL,(void *)producer,NULL);
pthread_join(p2,NULL);
pthread_create(&p3,NULL,(void *)consumer,NULL);
pthread_join(p3,NULL);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种特定情况下,使用 -pthread 优于 -lpthread。
Using -pthread is preferred to -lpthread in this specific case.
你是怎么编译的?
使用 gcc 程序名 -lpthread 进行编译
how are you compiling it??
compile using gcc program_name -lpthread
编译时在命令行中添加
-lpthread
,以便在链接时搜索pthreads库。Add
-lpthread
in the command line when compiling to search for the pthreads library when linking.