用信号量的方式实现打印1234567后打印7654321循环交替打印。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<head.h>
char buf[]="1234567";
sem_t sem;
void *callBack1(void *arg)
{
int i=0;
int s=strlen(buf)-1;
while(i<s)
{
int t=buf[i];
buf[i]=buf[s];
buf[s]=t;
i++;s--;
}
pthread_exit(NULL);
}
void *callBack2(void *arg)
{
printf("%s\n",buf);
sem_post(&sem);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
sem_init(&sem,0,1);
while(1)
{
pthread_t pid1,pid2;
sem_wait(&sem);
if(pthread_create(&pid2,NULL,callBack2,NULL)!=0)
{
fprintf(stderr,"failed __%d__\n",__LINE__);
return -1;
}
pthread_detach(pid2);
sem_post(&sem);
sem_wait(&sem);
if(pthread_create(&pid1,NULL,callBack1,NULL)!=0)
{
fprintf(stderr,"failed __%d__\n",__LINE__);
return -1;
}
pthread_join(pid1,NULL);
}
sem_destroy(&sem);
return 0;
}
创建两个线程,其中一个线程读取文件中的数据,另一个线程将读取到的内容打印到终端上,类似cat一个文件。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<head.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
int flag=0;
void *callBack1(void*arg)
{
int fd=open("./10.c",O_RDONLY);
if(fd<0)
{
ERR_MSG("open");
return NULL;
}
lseek(fd,0,SEEK_SET);
char c;
while(1)
{
pthread_mutex_lock(&mutex);
if(flag!=0)
pthread_cond_wait(&cond,&mutex);
ssize_t res=read(fd,&c,1);
if(res==0)
{
pthread_mutex_unlock(&mutex);
break;
}
*(char*)arg=c;
flag=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *callBack2(void*arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(flag!=1)
pthread_cond_wait(&cond,&mutex);
char c=*(char*)arg;
printf("%c",c);
flag=0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
char tmp_c=-1;
if(pthread_create(&tid1,NULL,callBack1,(void*)&tmp_c)!=0)
{
fprintf(stderr,"failed __%d__\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callBack2,(void*)&tmp_c)!=0)
{
fprintf(stderr,"failed __%d__\n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_cancel(tid2);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}