Bootstrap

操作系统实验十:进程同步 软件&硬件方法(DAY 55)

1:实验目的

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2:实验三

实验三:
在这里插入图片描述

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<unistd.h>
#include<stdbool.h>
static int tickets=20;
bool lock=false;

bool test_and_set(){
        if(lock==false){
                lock=true;
                return false;
        }

}

void *seller0(void *arg)
{
      while(tickets>0)
        {
                while(test_and_set());
                sleep(1);
                tickets--;
                printf("seller0: the remaining tickets:%d\n",tickets);
                lock=false;
        }
        sleep(1);
        return NULL;

}
void *seller1(void *arg)
{

        while(tickets>0)
        {
                while(test_and_set);

                sleep(1);
                tickets--;
                printf("seller1:the remaining tickets:%d\n",tickets);
                lock=false;
        }
        sleep(1);
        return NULL;
}
int main()
{

        pthread_t id[2];

        pthread_create(&id[0],NULL,seller0,NULL);
        pthread_create(&id[1],NULL,seller1,NULL);
        for(int i=0;i<2;i++)
        {
                pthread_join(id[i],NULL);
        }
                return 0;

在这里插入图片描述

3:实验四

在这里插入图片描述

#include<stdio.h>
#include<stdbool.h>
#include<pthread.h>
#include<unistd.h>
static int tickets = 20;

bool lock = false;
void swap(bool* a, bool* b)
{
	if (*a == true && *b == false)*a = false, * b = true;

	else if (*a == false && *b == true)*a = true, * b = false;
}

void* seller0() {

	while (tickets > 0)
	{
		bool key1 = true;
		do {
			swap(&key1, &lock);

		} while (key1);
		sleep(1);
		if (tickets > 0)
		{
			tickets--;
			printf("seller0: the remaining tickets:%d\n", tickets);
			lock = false;
		}
		sleep(1);

	}
	return NULL;
}

void* seller1() {
	while (tickets > 0)
	{
		bool key2 = true;
		do {
			swap(&key2, &lock);
		} while (key2);
		sleep(1);
		if (tickets > 0)
		{
			tickets--;
			printf("seller1: the remaining tickets: %d\n", tickets);
			lock = false;
		}
		sleep(1);
	}
	return NULL;
}

int main()
{
	pthread_t id[2];
	pthread_create(&id[0], NULL, seller0, NULL);
	pthread_create(&id[1], NULL, seller1, NULL);
	for (int i = 0; i < 2; i++)
	{
		pthread_join(id[i], NULL);
	}
	return 0;
}

在这里插入图片描述

;