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;
}