实验环境
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参数即可解决。