线程同步--信号量

#include 
#include 
#include 
#include 
#include 
#include 
#include 
sem_t sem1;
sem_t sem2;
char buff[128] = { 0 };
void* fun(void* arg)
{
	int fd = open("1.txt", O_RDWR | O_CREAT, 0600);
	assert(fd != -1);
	while (1)
	{
		sem_wait(&sem2);
		write(fd, buff, sizeof(buff));
		if (strncmp(buff, "end", 3) == 0)
		{
			break;
		}
		memset(buff, 0, 128);
		sem_post(&sem1);
	}
	sem_destroy(&sem1);
	sem_destroy(&sem2);
}
int main()
{
	pthread_t pid;
	sem_init(&sem1, 0, 1);
	sem_init(&sem2, 0, 0);
	int ret = pthread_create(&pid, NULL, fun, NULL);
	assert(ret == 0);
	while (1)
	{
		sem_wait(&sem1);
		fgets(buff, 128, stdin);
		printf("%s", buff);
		sem_post(&sem2);
		if (strncmp(buff, "end", 3) == 0)
			break;
	}
	pthread_exit(NULL);
}

你可能感兴趣的:(算法,linux,运维)