Лістинг програми б
#include<sched.h>
#include<stdio.h>
#include<unistd.h>
#include<semaphore.h>
#include<string.h>
#define NUMSTACK 5000
char stack[4][ NUMSTACK];
int count = 0;
int n;
char str[] = "";
char s[100][2];
static int mas[100];
int func(void *);
void clear();
void space();
sem_t sem1;
sem_t sem2;
int main()
{
printf("Enter string: ");
scanf("%s", str);
printf("Enter N:");
scanf("%d", &n);
int i;
printf("Enter symbols:\n");
for (i = 0; i < n; i++)
{
clear();
scanf("%c", &s[i][0]);
space();
scanf("%c", &s[i][1]);
}
sem_init(&sem1, 1, 1);
sem_init(&sem2, 1, 0);
for (i = 0; i < 4; i++)
{
char *tostack = stack[i];
clone(func, (void*)(tostack+NUMSTACK-1), CLONE_VM, NULL);
}
for (i = 0; i < 4; i++)
{
sem_wait(&sem2);
}
printf("Result:\n");
printf("%s\n", str);
return 1;
}
int func(void *param)
{
int tmpLen = strlen(str) / 4;
int start = count * tmpLen;
int end = start + tmpLen;
if (count == 3)
{
end = strlen(str);
}
int i, j;
for(i = start; i < end; i++)
{
for (j = 0; j < n; j++)
{
if ((str[i] == s[j][0]) && (mas[i] == 0))
{
str[i] = s[j][1];
mas[i] = 1;
}
}
}
count += 1;
sem_post(&sem1);
sem_post(&sem2);
return 1;
}
void clear()
{
while(getchar() != '\n');
}
void space()
{
while(getchar() != ' ');
}
Результат роботи програми
Висновок
Під час виконання лабораторної ознайомився з загальними принципами роботи семафорів. Навчився використовувати семафори для синхронізації процесів і потоків, і для захисту критичних секцій.
