【学习笔记】天嵌2440第三季下学期——linux多线程同步

实现线程同步可以通过低级的编程手段实现:

上代码:

#include <stdio.h>
#include <pthread.h>

pthread_t thread[2];
int number = 0;
pthread_mutex_t mut;

void studentA()
{
	int i;

	for (int i = 0; i < 5; i++)
	{
		//扫一次地
		printf("swaping%d\n", number);

		pthread_mutex_lock(&mut);

		number++;
		if (number >= 5)
			printf("studentA finish;\n");

		pthread_mutex_unlock(&mut);

		//休息一秒钟
		sleep(1);
	}
	//退出
	pthread_exit(NULL);

}

void studentB()
{
	while (1)
	{
		pthread_mutex_lock(&mut);
		
		//判断A同学是否已经扫完5次地
		if(number>=5){
			//拖地			
			number = 0;

			pthread_mutex_unlock(&mut);

			printf("student B has finish\n");

			break;
		}

		else{
			pthread_mutex_unlock(&mut);
			//睡眠2秒钟
			sleep(2);
		}

		pthread_exit(NULL);

	}

}

int main()
{
	pthread_mutex_init(&mut, NULL);

	//1、创建A同学进程
	pthread_create(&thread[0], NULL, studentA, NULL);

	//2、创建B同学进程
	pthread_create(&thread[1], NULL, studentB, NULL);

	//3、等待A同学进程结束
	pthread_join(thread[0], NULL);

	//4、等待B同学进程结束
	pthread_join(thread[1], NULL);
	
	return 0;
}

期间遇到核心段错误,经过gdb调适,发现是创建线程的传进了错误的参数形式:

pthread_create(thread[0], NULL, studentA, NULL);
线程的id必须要以地址的形式传入,上述代码已经订正。

但这种编程方式低效,可采用linux线程同步技术的特有函数:

pthread_cond_wait:

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int    pthread_cond_init(pthread_cond_t    *cond,    pthread_condattr_t *cond_attr);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
上述有两种初始化,据man手册提示,第一种属于静态初始化(initialized statically),教程采用这种方式。

上代码:

#include <stdio.h>
#include <pthread.h>

pthread_t thread[2];
int number = 0;
pthread_mutex_t mut;
pthread_cond_t cond_ready = PTHREAD_COND_INITIALIZER;

void studentA()
{
	int i;

	for (i = 0; i < 5; i++)
	{
		//扫一次地
		printf("swaping%d\n", i);

		pthread_mutex_lock(&mut);

		number++;
		if (number >= 5)
		{
			printf("student A finish;\n");
			pthread_cond_signal(&cond_ready);
		}
			

		pthread_mutex_unlock(&mut);

		//休息一秒钟
		sleep(1);
	}

	//退出
	pthread_exit(NULL);

}

void studentB()
{
	pthread_mutex_lock(&mut);

	if (number <= 5)
		pthread_cond_wait(&cond_ready, &mut);

	number = 0;

	pthread_mutex_unlock(&mut);
	printf("student B finish\n");

	//退出
	pthread_exit(NULL);
}

int main()
{
	pthread_mutex_init(&mut, NULL);

	//1、创建A同学进程
	pthread_create(&thread[0], NULL, studentA, NULL);

	//2、创建B同学进程
	pthread_create(&thread[1], NULL, studentB, NULL);

	//3、等待A同学进程结束
	pthread_join(thread[0], NULL);

	//4、等待B同学进程结束
	pthread_join(thread[1], NULL);
	
	return 0;
}

pthread_cond_wait函数里面会自动进行解锁与加锁访问共享资源number。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值