线程的同步互斥

 1.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<head.h>
char buf[]="1234567";
sem_t sem;
sem_t sem1;
void *callback(void *arg)
{

	while(1)
	{     
		sem_post(&sem1);
		{
			printf("%s\n",buf);
		}
		sem_post(&sem);

	}
	pthread_exit(NULL);
	return NULL;
}
void *callback1(void *arg)
{   
	while(1)
	{ 

		sem_wait(&sem);

		{
			int i=0;
			int j=6;

			while(i<j)
			{
				char t=buf[i];
				buf[i]=buf[j];
				buf[j]=t;
				i++;
				j--;
			}
		}
		sem_post(&sem1);

	}
	pthread_exit(NULL);
	return NULL;
}
int main(int argc, const char *argv[])
{ 
	
	if(sem_init(&sem,0,1)<0)
	{
		perror("sem_init");
		return -1;
	}
	if(sem_init(&sem1,0,0)<0)
	{
		perror("sem_init");
		return -1;
	}
	if(sem_init(&sem1,0,1)<0)
	{
		perror("sem_init");
		return -1;
	}

	pthread_t tid;
	if(pthread_create(&tid,NULL,callback,NULL)!=0)

	{
		printf("error");
		return -1;
	}


	pthread_t tid1;
	if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
	{
		printf("error");
		return -1;
	}

	while(1)
	{
	}
	sem_destroy(&sem);

	return 0;
}

2.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<head.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
char c;
int t=0;
	ssize_t res=2;
void* callBack(void* arg)
{	
	int fp=open("copy.c",O_RDONLY);
	if(fp<0)
	{
		ERR_MSG("open");
		return NULL;
	}
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(t!=0)
			pthread_cond_wait(&cond,&mutex);
		res=read(fp,&c,1);
		if(res==0)
		{
			pthread_exit(NULL);
		}
		t=1;
		pthread_cond_signal(&cond);

		pthread_mutex_unlock(&mutex);
	}
}
void* callBack2(void* arg)
{	
	while(1)
	{
		pthread_mutex_lock(&mutex);

		if(t!=1)
			pthread_cond_wait(&cond,&mutex);	

		write(1,&c,1);
		t=0;
		pthread_cond_signal(&cond);

	pthread_mutex_unlock(&mutex);
	}

}




int main(int argc, const char *argv[])
{
	pthread_t tid,tid2;
	if(pthread_create(&tid,NULL,callBack,NULL)!=0)
	{
		fprintf(stderr,"failed\n");
		return -1;
	}	
	if(pthread_create(&tid2,NULL,callBack2,NULL)!=0)
	{
		fprintf(stderr,"failed\n");
		return -1;
	}
	pthread_join(tid,NULL);
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
		
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值