LINUX下多线程编译问题 30
#include<stdio.h>#include<pthread.h>#include<unistd.h>#include<semaphore.h>void*produ...
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<semaphore.h>
void *producter_f (void *arg); //生产者线程函数
void *consumer_f (void *arg); //消费者线程函数
sem_t sem;
int running=1;
int main(void)
{
pthread_t consumer_t;
pthread_t producter_t;
sem_init(&sem,0,10); //信号量初始化
pthread_create(&producter_t,NULL,(void*)producter_f,NULL);
pthread_create(&consumer_t,NULL,(void*)consumer_f,NULL);
sleep(1);
running=0;
pthread_join(consumer_t,NULL);
pthread_join(producter_t,NULL);
sem_destroy(&sem);
return 0;
}
void *producter_f (void *arg)
{
int semval=3;
while(running)
{
usleep(2);
sem_post(&sem);
sem_getvalue(&sem,&semval);
printf("生产,总数量:%d\n",semval);
}
}
void *consumer_f (void *arg)
{
int semval=0;
while(running)
{
usleep(3);
sem_wait(&sem);
sem_getvalue(&sem,&semval);
printf("消费,总数量:%d\n",semval);
}
}
编译过程中总是出现各种变量未定义的现象,求解这是为什么 展开
#include<pthread.h>
#include<unistd.h>
#include<semaphore.h>
void *producter_f (void *arg); //生产者线程函数
void *consumer_f (void *arg); //消费者线程函数
sem_t sem;
int running=1;
int main(void)
{
pthread_t consumer_t;
pthread_t producter_t;
sem_init(&sem,0,10); //信号量初始化
pthread_create(&producter_t,NULL,(void*)producter_f,NULL);
pthread_create(&consumer_t,NULL,(void*)consumer_f,NULL);
sleep(1);
running=0;
pthread_join(consumer_t,NULL);
pthread_join(producter_t,NULL);
sem_destroy(&sem);
return 0;
}
void *producter_f (void *arg)
{
int semval=3;
while(running)
{
usleep(2);
sem_post(&sem);
sem_getvalue(&sem,&semval);
printf("生产,总数量:%d\n",semval);
}
}
void *consumer_f (void *arg)
{
int semval=0;
while(running)
{
usleep(3);
sem_wait(&sem);
sem_getvalue(&sem,&semval);
printf("消费,总数量:%d\n",semval);
}
}
编译过程中总是出现各种变量未定义的现象,求解这是为什么 展开
1个回答
展开全部
你编译的时候有加多扮答线程连接选项吗? 要加上 -lpthread 或者厅毁慧 -pthread (尽量选后者)
例如 gcc -pthread -o test main.cpp
另外你的线程创建的不对,函数指针不能强转类型(这里也不用转)余李
pthread_create(&producter_t,NULL,(void*)producter_f,NULL);
pthread_create(&consumer_t,NULL,(void*)consumer_f,NULL);
应该是
pthread_create(&producter_t,NULL,producter_f,NULL);
pthread_create(&consumer_t,NULL,consumer_f,NULL);
例如 gcc -pthread -o test main.cpp
另外你的线程创建的不对,函数指针不能强转类型(这里也不用转)余李
pthread_create(&producter_t,NULL,(void*)producter_f,NULL);
pthread_create(&consumer_t,NULL,(void*)consumer_f,NULL);
应该是
pthread_create(&producter_t,NULL,producter_f,NULL);
pthread_create(&consumer_t,NULL,consumer_f,NULL);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询