1.两个线程 A、B,要求A线程读取文件中的数据,B线程将读取到的数据打印到终端上。类似cat一个文件。
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
#include<strings.h>
pthread_mutex_t lock;
pthread_cond_t cond;
char str[20]="";
ssize_t res=-1;
int flag=0;
void *A(void *arg)
{
while(res!=0)
{
pthread_mutex_lock(&lock);
if(0!=flag)
{
pthread_cond_wait(&cond,&lock);
}
res=read(*(int*)arg,str,sizeof(str));
flag=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
pthread_exit(NULL);
}
void *B(void *arg)
{
while(res!=0)
{
pthread_mutex_lock(&lock);
if(1!=flag)
{
pthread_cond_wait(&cond,&lock);
}
write(1,str,res);
bzero(str,sizeof(str));
flag=0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
int file_r=open("./printf.c",O_RDONLY);
if(file_r<0)
{
printf("open");
return -1;
}
pthread_mutex_init(&lock,NULL);
pthread_cond_init(&cond,NULL);
pthread_t a,b;
if(pthread_create(&a,NULL,A,&file_r)!=0)
{
perror("pthread_create1");
return -1;
}
if(pthread_create(&b,NULL,B,NULL)!=0)
{
perror("pthread_create2");
return -1;
}
pthread_join(a,NULL);
pthread_join(b,NULL);
close(file_r);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
2.编写一个程序,开启3个 线程,这3个线程的ID分别为ABC,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示,如ABCABC……依次递推;
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond1,cond2;
int flag=1;
void *A(void *arg)
{
int i=0;
while(i<10)
{
pthread_mutex_lock(&lock);
if(1!=flag)
{
pthread_cond_wait(&cond1,&lock);
}
printf("A");
flag=2;
i++;
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&lock);
}
}
void* B(void* arg)
{
int i=0;
while(i<10)
{
pthread_mutex_lock(&lock);
if(2!=flag)
{
pthread_cond_wait(&cond2,&lock);
}
printf("B");
flag=3;
i++;
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&lock);
}
}
void* C(void *arg)
{
int i=0;
while(i<10)
{
pthread_mutex_lock(&lock);
if(3!=flag)
{
pthread_cond_wait(&cond1,&lock);
}
printf("C");
printf("\n");
flag=1;
i++;
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&lock);
}
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&lock,NULL);
pthread_cond_init(&cond1,NULL);
pthread_cond_init(&cond2,NULL);
pthread_t a,b,c;
if(pthread_create(&a,NULL,A,NULL)!=0)
{
perror("create1");
return -1;
}
if(pthread_create(&b,NULL,B,NULL)!=0)
{
perror("create2");
return -1;
}
if(pthread_create(&c,NULL,C,NULL)!=0)
{
perror("create3");
return -1;
}
pthread_join(a,NULL);
pthread_join(b,NULL);
pthread_join(c,NULL);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
return 0;
}