IOday7

1.创建两个线程,实现将一个文件的内容打印到终端上,类似cat一个文件
一个线程读取文件中的内容
另一个线程将读取到的内容打印到终端上。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

sem_t sem1,sem2;
pthread_t pth1,pth2;
char c='a';

void* cat(void* arg)
{
	lseek(*(int*)arg,0,SEEK_SET);
	while(1)
	{
		sem_wait(&sem1);
		size_t res=read(*(int*)arg,&c,1);	
		if(0==res)
			break;
		sem_post(&sem2);
	}
}
void* put(void* arg)
{
	while(1)
	{
		sem_wait(&sem2);
		printf("%c",c);
		sem_post(&sem1);
	}
}

int main(int argc, const char *argv[])
{
	int fp=open("./ex1.c",O_RDONLY);
	sem_init(&sem1,0,1);
	sem_init(&sem2,0,0);
	pthread_create(&pth1,NULL,cat,&fp);	
	pthread_create(&pth2,NULL,put,NULL);
	pthread_join(pth1,NULL);
	sem_destroy(&sem1);
	sem_destroy(&sem2);
	printf("\n打印完毕!\n");
	return 0;
}
//展示
/*
linux@linux:~/Desktop/demo3/day6$ gcc w2.c -pthread
linux@linux:~/Desktop/demo3/day6$ ./a.out 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

pthread_mutex_t mutex;


//------------------>前半部分
void* front(void* arg)
{
	int len=*((int*)arg+1);
	int fp=*((int*)arg);
	int fp1=*((int *)arg+2);
	pthread_mutex_lock(&mutex);
	lseek(fp,0,SEEK_SET);
	lseek(fp1,0,SEEK_SET);
	for(int i=0;i

2. 用条件变量的方式实现:现有ID号为a b c的三个线程,每个线程的任务都是循环打印自己id号,要求打印的顺序为abc

#include 
#include 
#include 
#include 
#include 

sem_t sem1,sem2,sem3;
pthread_t pth1,pth2,pth3;
void* out1(void* argv)
{
	while(1)
	{
		sem_wait(&sem1);
		printf("1---------->%ld\n",pth1);
		sem_post(&sem2);
	}
}
void* out2(void* argv)
{
	while(1)
	{
		sem_wait(&sem2);
		printf("2---------->%ld\n",pth2);
		sem_post(&sem3);
	}
}
void* out3(void* argv)
{
	while(1)
	{
		sem_wait(&sem3);
		printf("3---------->%ld\n",pth3);
		sem_post(&sem1);
		putchar(10);
	}
}
int main(int argc, const char *argv[])
{
	sem_init(&sem1,0,1);
	sem_init(&sem2,0,0);
	sem_init(&sem3,0,0);
	pthread_create(&pth1,NULL,out1,NULL);
	pthread_create(&pth2,NULL,out2,NULL);
	pthread_create(&pth3,NULL,out3,NULL);
	pthread_join(pth1,NULL);
	sem_destroy(&sem1);
	sem_destroy(&sem2);
	sem_destroy(&sem3);
	return 0;
}
//展示
/*
linux@linux:~/Desktop/demo3/day6$ gcc w3.c -pthread
linux@linux:~/Desktop/demo3/day6$ ./a.out 
1---------->140418605229824
2---------->140418596837120
3---------->140418519922432

1---------->140418605229824
2---------->140418596837120
3---------->140418519922432

1---------->140418605229824
2---------->140418596837120
3---------->140418519922432


*/

你可能感兴趣的:(c++,c语言,c#)