diff --git a/lab0/hello/a.out b/lab0/hello/a.out new file mode 100755 index 000000000..8b76cd745 Binary files /dev/null and b/lab0/hello/a.out differ diff --git a/lab0/hello/empty b/lab0/hello/empty new file mode 100644 index 000000000..e69de29bb diff --git a/lab0/hello/hello_world b/lab0/hello/hello_world new file mode 100755 index 000000000..8b76cd745 Binary files /dev/null and b/lab0/hello/hello_world differ diff --git a/lab0/src/hello.c b/lab0/hello/newhello.c similarity index 100% rename from lab0/src/hello.c rename to lab0/hello/newhello.c diff --git a/lab0/src/hello b/lab0/src/hello new file mode 100755 index 000000000..c71ae2565 --- /dev/null +++ b/lab0/src/hello @@ -0,0 +1,6 @@ +#include + +int main() +{ + printf("Hello World!\n"); +} \ No newline at end of file diff --git a/lab1/src/average.sh b/lab1/src/average.sh new file mode 100755 index 000000000..a2a3c6411 --- /dev/null +++ b/lab1/src/average.sh @@ -0,0 +1,13 @@ +sum=0 +count=0 + +for arg in "$@" +do + sum=$((sum + arg)) + count=$((count + 1)) +done + +average=$((sum / count)) + +echo "Количество: $count" +echo "Среднее: $average" \ No newline at end of file diff --git a/lab1/src/cake_rhymes.txt b/lab1/src/cake_rhymes.txt index 8a0141bf4..265bdd67a 100755 --- a/lab1/src/cake_rhymes.txt +++ b/lab1/src/cake_rhymes.txt @@ -2141,4 +2141,4 @@ Let's spend some cake From "I Meant You No Harm/Jimmy's Rap [Eddie Murphy]" by Various Artists: Listen, Jimmy wanna rib, Jimmy wanna stake, -Jimmy wanna piece o' your chocolate cake! \ No newline at end of file +Jimmy wanna piece o' your chocolate cake! diff --git a/lab1/src/cat b/lab1/src/cat new file mode 100644 index 000000000..e69de29bb diff --git a/lab1/src/date.sh b/lab1/src/date.sh new file mode 100755 index 000000000..78b22b868 --- /dev/null +++ b/lab1/src/date.sh @@ -0,0 +1,8 @@ +current_path=$(pwd) +echo "Текущий путь: $current_path" + +current_datetime=$(date) +echo "Текущая дата и время: $current_datetime" + +echo "Переменная окружения PATH:" +echo "$PATH" \ No newline at end of file diff --git a/lab1/src/file.txt b/lab1/src/file.txt new file mode 100644 index 000000000..e69de29bb diff --git a/lab1/src/numbers.txt b/lab1/src/numbers.txt new file mode 100644 index 000000000..6f809d399 --- /dev/null +++ b/lab1/src/numbers.txt @@ -0,0 +1,38 @@ + -2052327929 305313122 1710747617 -447613493 + -313123026 -548928818 -956788863 -743001018 + -1744759366 -118652918 -1829660190 -1844615270 + -1509313493 -427771341 1062937898 1824819511 + -843800214 1082206093 383192283 862209460 + 1173114215 527834824 43319982 794503944 + -1906875220 -1777862017 903828368 1465672524 + 260585254 -1027851049 1075490081 -1646011538 + 1696275105 -263419061 -1556047791 1787808342 + 907456296 -1981479094 1459165564 406217401 + -1345096005 1285216707 -165944879 -456595589 + 643708491 -820103845 -936157586 -316027939 + 659574036 171795479 -258303041 1564078749 + -644199081 -1041994536 -1002657168 -491651272 + -182483842 1510071333 -859581615 -956758217 + 68601168 849537820 -1039043339 -1869906744 + 716751050 -1564301193 -1252282184 823334594 + 1549021612 -1886693599 751631666 -1724643184 + -706318923 1242321336 1461296801 1011789853 + 1392037245 1190641597 -1364451949 -1504471030 + 1132028689 971592827 -884161693 1152913838 + 744163316 346212835 -696212065 1760132864 + -352693723 1985571736 835783877 -1273660573 + -655178014 -1213184821 675088096 -381402664 + -703386773 59883766 -711451025 1640948178 + 1417854370 32868656 644481753 -1268824927 + -1380175048 1895416202 574489454 154158005 + -1918304011 -204796523 -734469036 400680589 + 5103190 624075437 -596690411 -1285112967 + 2111244731 -318083076 -269495340 1429528656 + 474601737 1277783648 -894177877 -578765142 + -1281997175 -651733918 1133053749 -186408248 + 1561449653 432220552 388551490 -1262827756 + -2144512146 1471877951 148957167 1581252722 + 1813552769 -1359072653 -1716099336 -1797210878 + 989657636 634415298 -1734158945 -256685798 + 1086075533 -1280513553 406068273 -708678475 + 1518191518 -1989649904 \ No newline at end of file diff --git a/lab1/src/show_all b/lab1/src/show_all new file mode 100755 index 000000000..98b3ee74d --- /dev/null +++ b/lab1/src/show_all @@ -0,0 +1,4 @@ +#!/bin/bash +pwd +date +echo "I have $1 in my pocket" diff --git a/lab1/src/with_cake.txt b/lab1/src/with_cake.txt new file mode 100644 index 000000000..61bbb8f60 --- /dev/null +++ b/lab1/src/with_cake.txt @@ -0,0 +1,381 @@ +Here is some milk and oaten cake. +And a halfpenny cake, +I'll give you a cake +She takes the cake - +One day it's honey and raisin cake, +Don't that take the cake +With the big bad devil's food cake. +Sweet as a cake +I say let 'em all eat cake. +And baked him a cake +Is it the baker who gave you a cake +Was sugar cake +We ask them for bread and get ?let them eat cake? +when it comes to brains I take the cake +The sacramental cake: +Well, I'll be a lawman's piece of cake +And the maid comes in with coffee and cake +is just icing on the cake, +Nibblin' on sponge cake +And when you stand before the candles on a cake +There's no bread, let them eat cake +In the wedding cake? +I want to be the girl with the most cake +This is what you call presidential cake up +I light the candles and I cut the cake +I put my face down in the cake +Back inside Sam, throw away your cake +What's up? They all want the cake +And I will bake a sugar cake +Baby Cham and Foxy Brown, ah we take the cake +A piece of your cake? +He was the one afraid to cut the cake +Right, look, I was out of town getting cake +Well did he leave your pretty fingers lying in the wedding cake +A sell dem sell very cheap fi fruit cake +But I wake, mountains pop out of the cake +Rubberbands round cash im makin cake +We get a bit of the good life, a piece of the cake +Mary antoinette enjoyed her cake +After Canada the USA's a piece of cake +And ain't no fake gonna steal my cake +Homie over here's tryin to take his cake +makes you humble for the pot, I know he's accustomed to the cake +You traded in your real man for trailer life and funnel cake +Want a big piece of the cake +Is sweeter than the cake +I like cake, +I'll cut out cake +Don't need candles and cake +I'm gonna be on you like a fat kid on cake! +Becomes a piece of cake +So damp and rich a cake- +Back the cake, +The way John Goodman needs cake +this dessert, takes the cake, +Becomes a piece of cake +While he gorges on truffles and cake. +When there was still one piece of cake +when it comes to brains I take the cake +That's nice, but it's just icing on the cake. +Not an enticing effect to be icing your face like a cake +Some take just apple pie, some take just cake +Happy birthday darling, I've no present, no fancy cake +Vanilla fudge and wedding cake +We ought to bake a sunshine cake, +[We ought to bake a sunshine cake] +[So why not bake a sunshine cake,] +I thought the world was sugar cake +before the candles on a cake +He's a piece of cake +It's as easy as pie, and as simple as cake +Matter fact make me a birthday cake +Celebrate, drink up, get your cake up, +Did you leave your pretty fingers flying in the wedding cake? +Spaghetti and cookies and cake +About the time the couple cut the cake +and janey's fingers were in the cake +While blowing out the candles on a birthday cake +Blow out the candles on the cake +Running this hotel is no piece of cake +some folks like cake +He said don't worry it's a piece of cake +I popped out from a cake +Poor old papa carved the turkey and little sister cut the cake +Too many reaching for a piece of cake +you sick little cup cake, +Now it's time to light another candle on the cake +Why don't you take a stone and eat it just as if it were a cake +It ain't hard to tell, you know I get cake +It all comes with the wedding cake +But you take the cake +I live in a cake, +I make spaghetti, she brings cake +I had to leave before they even cut the cake. +I'm the one that get the cake +The streets is talkin and they tellin me to go get that cake +I swear it ain't been the same ever since I got cake +I'm on a paper chase for pies, yeah that cookies and cake +I'm on a paper chase for pies, yeah that cookies and cake +And you're filling your fat face with every different kind of cake +You serve me up with cake +Well all that icing and all that cake, +in the wedding cake? +This is what you call presidential cake up +This is what you call presidential cake up +Remember I'm gonna spend my cake +Yeah I VV'd the stones, dog I'm into cake +You like the frosting, you just bought the cake +The kids won't eat my charcoal cake +Playin' patty cake (patty cake) +Thinking about you is the icing on the cake. +Now they're out in the woods eating ice-cream and cake +Sweeter than a buckwheat cake +About the time the couple cut the cake +It's time to get wise, rise, and cut the cake +iceing on a cake +Carved our initials on top of the cake +Here on earth I'll have my cake +I'm the candles on you're cake +when do i jump out of the cake +famous for his cake +Where we're all gonna have a cake. +Can I have another piece of chocolate cake? +Why my homeys ain't get that cake +Half baked, eatin' ganja cake +Janey's fingers were in the cake +If I told you what I make, everytime I flip a cake +i lived in a cake +Lost in coma and covered in cake. +All's fair in love and war, piece of cake +Claiming the got backs but they never share their cake +Give me a cake +And a piece of the wedding cake +And Janey's fingers were in the cake +Ain't no piece of cake +it hasn't always been a piece of cake +Did you leave your pretty fingers lying in the wedding cake? +on my way up, gettin my cake up +Just icing on the cake +Want you to come get a file in your cake +He lost his slice of the eternal cake +The girl in the cake +As we keep you wired, so up the stakes, cut the cake +dem sin a pile up on dem and it a cake up +Won't feed the birds bread boys, let them eat cake +I'll make my money, set my cake up +Now, let's set it straight, B-I-G don't cuff or cake +People say you can't have your cake +Some songs sound like cake +straight to the hood to see some new cake +I gotta stay awake when I hold the cake +Those who could relate know the world ain't cake +Where you said put the cake +soup and his kingly cake +spaghetti and cookies and cake +He said you try it, I said it's a piece of cake +Too much sugar and too much cake +Are you made or broken by the birthday cake? +Thirty-nine (39) candles burnt out on a cake +Sweet carob rice cake +Well, she go to see the baker when she wants a cake +Traveling and stacking the cake +I've got some mochomo cake +now my cake up +Man, this really takes the cake +You bake my cake +Cutting the cake +I'm cake +see the sugar bowl do a tootsi roll and the bad devils food cake +I wanna have my piece of cake +Yeah and I'm about cake +Violet wants ice cream, Violet wants cake +I want the whole of the cake +For the birthday cake +Been like this ever since I got my cake up +I flashed a grin and said, Jack this is gonna be a piece of cake +They do whatever it takes to keep a lil' cake +Baking up a Martian cake +but the something on the side is what takes the cake +These limitations that burden me must be the icing on your cake +To much icind on the cake +But your kiss is sweeter than the cake +My heart, my soul, my candy, my cake +I'm a bake a hater cake today +seems like a cake +Being that we ugly, it ain't a piece of cake. +I'm selfish got to have the pie and the whole cake +comin' around for devil's cake +There were no balloons or cake +Dark, rich and thick like a fresh baked cake +I'm craving the taste of the cake +Where you goin'? Where I'm goin? Finna get the cake!/ +If I knew you were comin' I'd've baked a cake +Ate up all of the wedding cake, Uh-huh. +Eat it like a piece of cake +Her name is Little Debbie, and I love her cake +Light a fuse, bake a cake +Thirty-one candles on her birthday cake +You'll miss my carrot cake +I love you like a fat kid love cake +First they brought in tay and cake +Antagonizing pressure is the icing on the cake +I eat my cake +The kids won't eat my charcoal cake +But this job ain't all cookies and cake +They brought in tea and whisky cake. +All the world is birthday cake +I ain't tryina sell my soul but I'm tryina get this cake +And I will bake a sugar cake +Consider my raw demeanor the icing on the cake +Life is just a piece of cake +'cause wit whipped cream on em, they taste just like cake +Most friends were broke, only a couple had cake +I'd celebrate at your wake, I'd bake myself a cake +I'm just tryin' to be the great, tryin' to get a piece of cake +You can't get a slice if you don't bake the cake +If 50 was Puffy, you'd run and go get him a cheese cake +But bein an entertainer puts the icin on the cake +Your pockets we shake for cake +So just cut the stupid cake +But this one takes the cake +And ain't no fake gonna steal my cake +makes you humble for the pot, I know he's accustomed to the cake +I'm a man - I insist you insist on a piece of cake +You're a man - You insist I insist on a piece of cake +"Let 'em eat cake." +I don't want a piece of your cake! +Tryin' not to go to jail, tryin' not to cake up +We smash for cake +In an old age pension-less cake +Vanilla fudge and wedding cake +(You are just the icing to put on my cake) +Eat a crocodile cake +You have let us eat the cake +To make up for that piece of cake +Matter fact make me a birthday cake +And start to bake a sugar cake +ha get your cake up +Get cha cake up +Somebody's been digging 'round in my cake. +When a waiter brought out a big strawberry cake +And I quietly finished my strawberry cake +There's too much motherfuckin' paper to cake up +stake and a layer cake. +The jingoistic cake +Black the colour icing on our cake +and janey's fingers were in the cake +The layers on the cake +I'm a cup of hot coffee, I'm a piece of cake. +I can fill your larder, I'm a piece of cake. +you can bowl me over, I'm a piece of cake. +Been piece of cake +He said don't worry it's a piece of cake +Four and twenty blackbirds in a cake +odd years without having my cake up +You dudes is cake +Then blow out the candles, and have a piece of cake! +All I found was that old piece of our wedding cake. +The few hours off to eat wedding cake +But I hear tell someone's been diggin round in my cake +Come with the wedding cake +Comes with the wedding cake +a piece of cake +Red Velvet cake +Joy and tears come with the wedding cake. +It all comes with the wedding cake... +I eat it up and take the cake +In time I've earned my cake, +Today my son birthday and I can't even buy a cake +I had to leave before they even cut the cake. +She in her birthday suit cause of the damn cake +You serve me up with cake +Who ate every crumb of the wedding cake. +Cuz wit whipped cream on em, they taste just like cake +The safe in the floor with a life time of cake +Him and Genius flew back from, Uganda black, gettin' that cake +Just the sweet watermelon and the buckwheat cake +Gotta get my cake up +Marie said "Just let them eat cake" +Four and twenty blackbirds in a cake +for a cup of cold coffee and a piece of cake. +I will be the file in the cake +getting that independent cake +I'm gonna bake me her favorite cake +But wait, he got singles in his cake +I got locked by the jake, you was right I had to take the whole cake +I'll screw my only brother for even a glimpse at a piece of the cake +Leaving all the yellow roses on her wedding cake +They just get the news and the ones in power always get the cake +Thinking about you is the icing on the cake. +It's time to get wise, rise, and cut the cake +Becomes a piece of cake +Did we mention each meal would be full of fun cake? +Mek all mi allstar cake +It's gonna melt the icing on our cake +Mind right, cake up +Birthday wordplay, piece of cake +heaven is a beef-cake. +Beef cake? +Triple beam wit da lean, the man wit da cake +I believe in birthday cake +And I can't be runnin late cause I'm about that cake +Sweet potatoe cake +The only thing she'd make was cake, +Four and twenty blackbirds in a cake +Janey's fingers were in the cake +I bake Donald Trump cake +so i get up off my bump and go get that cake +But im still gettin cake +I'm your cream cake +Before you hibernate and you come out a crab cake" +When I was nine I said a rhyme by putting candles on my cake +I love you like a fat kid love cake +If you bring enough for them, you can have your cake +And Janey's fingers were in the cake +You take the cake. +Your style is all tissue, chocolate fudge cream cake +Luck seemed to serve us a slice of life's cake +Baby don't stop, take it to the top, eat it like a piece of cake +She might pop out of the top of a birthday cake +Come with the wedding cake. +I didn't know this was the place I'd get my piece of the cake +Or feed you poison birthday cake +i`m popping out of my rebirthday cake +I bang up like a birthday cake +Watch me bake my own cake +Ended up in folsom but the file was in the cake +The camel's tellin' you to come on, you had to cake it +You have sex with cake +dem sin a pile up on dem and it a cake up +Won't feed the birds bread boys, let them eat cake +From "Fruitcake" by Eraserheads: +Life is a piece of cake +And start to bake a sugar cake +It's no piece of cake, +I say stick together God until y'all cake up +That way they get the biggest slice of the cake +ni mamul bbetnun kosun negenun piece of a cake +Those who could relate know the world ain't cake +Ice cream and cake. +Whether we have not or have cake +For a slice of cake +Are you made or broken by the birthday cake? +And I share her love of wine and cake +Same knife that cuts your throat divides the cake +well, first she brought out tea and cake, +Still you want to have and eat your cake +Well I found a match and wrote these words on your cake +and the brook valley man dem need a slice a di cake +And a red-head freckled face blows out the candles on his birthday cake +Cutting the cake +Becomes a piece of cake +But your friends are hungry so just cut the stupid cake. +You just keep on trying till you run out of cake +Gave up your lot for a bite of the cake +If I kill, yo, I'm doin' so for the cake +My piece of the cake +It's a'one big... one big... one big... cake! +Like dropping out of weight while you're trying to have your cake +You know it's all for the cake, yeah it's all for the cake +That's when the voice began to barter with the promise of cake. +She could almost taste the cake. +on my birthday give me a burger not a cake +Love burns all and hate takes the cake +And we would sail under the stars eating strawberry cake +I'm a bake a hater cake today +Then its kissy smiley, fake fake fake, Like a cake +And dream of mama's chocolate cake +Hey producer cut me on the cake +Everyday is a grind, gotta get the cake up +We drank a lot of stout and ate a lot of cake! +He said baby you'r so hott you could bake my cake +till you run out of cake. +I'm craving the taste of the cake +I shake the jake to get the cake +Baked inside a fudge cake. +Ain't nothing but a fruit cake +Out of a ginger cake +Won't even buy me cheap, cheap cake +Let's spend some cake +Jimmy wanna piece o' your chocolate cake! diff --git a/lab2/src/revert_string/librevstr.a b/lab2/src/revert_string/librevstr.a new file mode 100644 index 000000000..b3b84fe85 Binary files /dev/null and b/lab2/src/revert_string/librevstr.a differ diff --git a/lab2/src/revert_string/librevstrdin.so b/lab2/src/revert_string/librevstrdin.so new file mode 100755 index 000000000..7b74e7480 Binary files /dev/null and b/lab2/src/revert_string/librevstrdin.so differ diff --git a/lab2/src/revert_string/result b/lab2/src/revert_string/result new file mode 100755 index 000000000..b50c91dd4 Binary files /dev/null and b/lab2/src/revert_string/result differ diff --git a/lab2/src/revert_string/resultdin b/lab2/src/revert_string/resultdin new file mode 100755 index 000000000..7279a5843 Binary files /dev/null and b/lab2/src/revert_string/resultdin differ diff --git a/lab2/src/revert_string/resultstatic b/lab2/src/revert_string/resultstatic new file mode 100755 index 000000000..338bb1aec Binary files /dev/null and b/lab2/src/revert_string/resultstatic differ diff --git a/lab2/src/revert_string/revert_string.c b/lab2/src/revert_string/revert_string.c index e257bbe26..2844af2c3 100755 --- a/lab2/src/revert_string/revert_string.c +++ b/lab2/src/revert_string/revert_string.c @@ -1,7 +1,16 @@ #include "revert_string.h" +#include void RevertString(char *str) { - // your code here + int length = strlen(str); + int i, j; + char temp; + + for (i = 0, j = length - 1; i < j; i++, j--) { + temp = str[i]; + str[i] = str[j]; + str[j] = temp; + } } diff --git a/lab2/src/revert_string/revert_string.o b/lab2/src/revert_string/revert_string.o new file mode 100644 index 000000000..03a3d0bfb Binary files /dev/null and b/lab2/src/revert_string/revert_string.o differ diff --git a/lab2/src/swap/result b/lab2/src/swap/result new file mode 100755 index 000000000..f8358eb94 Binary files /dev/null and b/lab2/src/swap/result differ diff --git a/lab2/src/swap/swap.c b/lab2/src/swap/swap.c index 38e97928c..06c687307 100755 --- a/lab2/src/swap/swap.c +++ b/lab2/src/swap/swap.c @@ -2,5 +2,7 @@ void Swap(char *left, char *right) { - // ваш код здесь + char temp = *right; + *right = *left; + *left = temp; } diff --git a/lab2/src/tests/Unit b/lab2/src/tests/Unit new file mode 100755 index 000000000..c7a2eaca5 Binary files /dev/null and b/lab2/src/tests/Unit differ diff --git a/lab2/src/tests/Unittests b/lab2/src/tests/Unittests new file mode 100755 index 000000000..c7a2eaca5 Binary files /dev/null and b/lab2/src/tests/Unittests differ diff --git a/lab2/src/tests/revert_string.h b/lab2/src/tests/revert_string.h new file mode 100755 index 000000000..782a130f3 --- /dev/null +++ b/lab2/src/tests/revert_string.h @@ -0,0 +1,6 @@ + +/* function to revert string */ +void RevertString(char *str); + + + diff --git a/lab3/src/find_min_max.c b/lab3/src/find_min_max.c index 6662a8fba..fb1dadc9c 100755 --- a/lab3/src/find_min_max.c +++ b/lab3/src/find_min_max.c @@ -7,6 +7,14 @@ struct MinMax GetMinMax(int *array, unsigned int begin, unsigned int end) { min_max.min = INT_MAX; min_max.max = INT_MIN; - // your code here + for (unsigned int i = begin; i <= end; i++) { + if (array[i] < min_max.min) { + min_max.min = array[i]; + } + if (array[i] > min_max.max) { + min_max.max = array[i]; + } + } + return min_max; } diff --git a/lab3/src/find_min_max.o b/lab3/src/find_min_max.o new file mode 100644 index 000000000..091636729 Binary files /dev/null and b/lab3/src/find_min_max.o differ diff --git a/lab3/src/makefile b/lab3/src/makefile index 1538d9699..959664279 100755 --- a/lab3/src/makefile +++ b/lab3/src/makefile @@ -15,3 +15,18 @@ find_min_max.o : utils.h find_min_max.h clean : rm utils.o find_min_max.o sequential_min_max parallel_min_max + +task4: sequential_min_max + $(CC) -o task4 task4.c + ./task4 + + +# Запуск 2-3 задания +make build_bin: + $(CC) find_min_max.c parallel_min_max.c utils.c -o task3 + +make up_by_files: build_bin + ./task3 --seed 2 --array_size 1000 --pnum 4 --by_files + +make up_by_pipes: build_bin + ./task3 --seed 2 --array_size 1000 --pnum 4 diff --git a/lab3/src/minmax_0.txt b/lab3/src/minmax_0.txt new file mode 100644 index 000000000..aefbfe793 --- /dev/null +++ b/lab3/src/minmax_0.txt @@ -0,0 +1 @@ +11719343 2139613154 diff --git a/lab3/src/minmax_1.txt b/lab3/src/minmax_1.txt new file mode 100644 index 000000000..db23ac8c3 --- /dev/null +++ b/lab3/src/minmax_1.txt @@ -0,0 +1 @@ +19296505 2145219718 diff --git a/lab3/src/minmax_2.txt b/lab3/src/minmax_2.txt new file mode 100644 index 000000000..1ab8ee138 --- /dev/null +++ b/lab3/src/minmax_2.txt @@ -0,0 +1 @@ +4344352 2144848934 diff --git a/lab3/src/minmax_3.txt b/lab3/src/minmax_3.txt new file mode 100644 index 000000000..b770ed712 --- /dev/null +++ b/lab3/src/minmax_3.txt @@ -0,0 +1 @@ +6966532 2146294955 diff --git a/lab3/src/parallel_min_max.c b/lab3/src/parallel_min_max.c index acb35ec64..cb4b72b55 100755 --- a/lab3/src/parallel_min_max.c +++ b/lab3/src/parallel_min_max.c @@ -42,22 +42,34 @@ int main(int argc, char **argv) { seed = atoi(optarg); // your code here // error handling + if (seed <= 0) { + printf("seed is a positive number\n"); + return 1; + } break; case 1: array_size = atoi(optarg); // your code here // error handling + if (array_size <= 0) { + printf("array_size is a positive number\n"); + return 1; + } break; case 2: pnum = atoi(optarg); // your code here // error handling + if (pnum <= 0) { + printf("pnum is a positive number\n"); + return 1; + } break; case 3: with_files = true; break; - defalut: + default: printf("Index %d is out of options\n", option_index); } break; @@ -84,13 +96,29 @@ int main(int argc, char **argv) { return 1; } + // Выделение памяти для массива int *array = malloc(sizeof(int) * array_size); + // Генерация значений GenerateArray(array, array_size, seed); + // Инициализация активных дочерних процессов int active_child_processes = 0; struct timeval start_time; gettimeofday(&start_time, NULL); + // Создаем каналы синхронизации процессов + int **pipes = malloc(pnum * sizeof(int *)); + for (int i = 0; i < pnum; i++) { + pipes[i] = malloc(2 * sizeof(int)); + } + + for (int i = 0; i < pnum; i++) { + if (pipe(pipes[i]) == -1) { + perror("pipe"); + return 1; + } + } + for (int i = 0; i < pnum; i++) { pid_t child_pid = fork(); if (child_pid >= 0) { @@ -98,13 +126,42 @@ int main(int argc, char **argv) { active_child_processes += 1; if (child_pid == 0) { // child process - + + // Определяем размер подмассива + int mini_array_size = array_size / pnum; + int begin = i * mini_array_size; + int end; + + if (i == pnum - 1) { + end = array_size - 1; + } else { + end = (i + 1) * mini_array_size; + } // parallel somehow + struct MinMax array_minmax = GetMinMax(array, begin, end); + + + // Создание файлов и запись в них результатов каждого дочернего процесса if (with_files) { // use files here + char filename[256]; + snprintf(filename, sizeof(filename), "minmax_%d.txt", i); + + FILE *file = fopen(filename, "w"); + if (file == NULL) { + perror("fopen"); + return 1; + } + + fprintf(file, "%d %d\n", array_minmax.min, array_minmax.max); + + fclose(file); } else { // use pipe here + close(pipes[i][0]); // Закрыть чтение из pipe + write(pipes[i][1], &array_minmax, sizeof(struct MinMax)); + close(pipes[i][1]); // Закрыть запись в pipe } return 0; } @@ -115,10 +172,22 @@ int main(int argc, char **argv) { } } + // Пока есть активные процессы while (active_child_processes > 0) { // your code here + int status; + pid_t finished_pid = wait(&status); + + if (finished_pid > 0) { + active_child_processes -= 1; - active_child_processes -= 1; + if (WIFEXITED(status)) { + int exit_status = WEXITSTATUS(status); + } + } else { + perror("wait"); + return 1; + } } struct MinMax min_max; @@ -131,12 +200,38 @@ int main(int argc, char **argv) { if (with_files) { // read from files + char filename[256]; + snprintf(filename, sizeof(filename), "minmax_%d.txt", i); + + // Открытие файла для чтения + FILE *file = fopen(filename, "r"); + if (file == NULL) { + perror("fopen"); + return 1; // Обработка ошибки открытия файла + } + + // Чтение минимума и максимума из файла + int min, max; + fscanf(file, "%d %d", &min, &max); + + // Закрытие файла + fclose(file); + + // Сравнение с глобальным минимумом и максимумом + if (min < min_max.min) min_max.min = min; + if (max > min_max.max) min_max.max = max; + } else { // read from pipes + close(pipes[i][1]); // Закрыть запись в pipe + struct MinMax array_minmax; + read(pipes[i][0], &array_minmax, sizeof(struct MinMax)); + close(pipes[i][0]); // Закрыть чтение из pipe + + if (array_minmax.min < min_max.min) min_max.min = array_minmax.min; + if (array_minmax.max > min_max.max) min_max.max = array_minmax.max; } - if (min < min_max.min) min_max.min = min; - if (max > min_max.max) min_max.max = max; } struct timeval finish_time; @@ -145,6 +240,10 @@ int main(int argc, char **argv) { double elapsed_time = (finish_time.tv_sec - start_time.tv_sec) * 1000.0; elapsed_time += (finish_time.tv_usec - start_time.tv_usec) / 1000.0; + for (int i = 0; i < pnum; i++) { + free(pipes[i]); + } + free(pipes); free(array); printf("Min: %d\n", min_max.min); diff --git a/lab3/src/sequential_min_max b/lab3/src/sequential_min_max new file mode 100755 index 000000000..0d99fda03 Binary files /dev/null and b/lab3/src/sequential_min_max differ diff --git a/lab3/src/sequential_min_max.c b/lab3/src/sequential_min_max.c index e6bd2d866..3e5978e98 100755 --- a/lab3/src/sequential_min_max.c +++ b/lab3/src/sequential_min_max.c @@ -10,21 +10,30 @@ int main(int argc, char **argv) { return 1; } + //преобразует аргумент seed в целое число и проверяет, что оно положительно. int seed = atoi(argv[1]); if (seed <= 0) { printf("seed is a positive number\n"); return 1; } + //Преобразует аргумент arraysize в целое число и проверяет, что оно положительно. int array_size = atoi(argv[2]); if (array_size <= 0) { printf("array_size is a positive number\n"); return 1; } + //Выделяет память для массива array размером arraysize элементов с int *array = malloc(array_size * sizeof(int)); + + //Генерирует массив с помощью функции GenerateArray, используя переданный seed. GenerateArray(array, array_size, seed); + + //Вызывает функцию GetMinMax для нахождения минимального и максимального элементов struct MinMax min_max = GetMinMax(array, 0, array_size); + + //Освобождает память, выделенную для массива array. free(array); printf("min: %d\n", min_max.min); diff --git a/lab3/src/task3 b/lab3/src/task3 new file mode 100755 index 000000000..6cdcc6261 Binary files /dev/null and b/lab3/src/task3 differ diff --git a/lab3/src/utils.o b/lab3/src/utils.o new file mode 100644 index 000000000..53c641244 Binary files /dev/null and b/lab3/src/utils.o differ diff --git a/lab4/src/Makefile b/lab4/src/Makefile new file mode 100644 index 000000000..33521ef7d --- /dev/null +++ b/lab4/src/Makefile @@ -0,0 +1,43 @@ +CC=gcc +CFLAGS=-I. + +task1: + ./parallel_min_max --seed 42 --array_size 100 --pnum 5 --timeout 5 + +zombie: zombie.c + $(CC) -o zombie zombie.c + +zombie_print: + ./zombie & + ps -l + +cleanzombie: + rm zombie + +process_memory : process_memory.c + $(CC) -o process_memory process_memory.c $(CFLAGS) + +psum : Summa.o utils.o Summa.h utils.h + $(CC) -o psum utils.o Summa.o parallel_sum.c -lpthread $(CFLAGS) + +psum_print: psum + ./psum --seed 4 --array_size 1000 --threads_num 4 + +up_parallel_min_max: + ./parallel_min_max --seed 2 --array_size 1000 --pnum 4 --timeout 10 + +utils.o : utils.h + $(CC) -o utils.o -c utils.c $(CFLAGS) + +Summa.o : Summa.h + $(CC) -o Summa.o -c Summa.c $(CFLAGS) + +find_min_max.o : utils.h find_min_max.h + $(CC) -o find_min_max.o -c find_min_max.c $(CFLAGS) + +parallel_min_max : utils.h find_min_max.h + $(CC) -o parallel_min_max utils.o find_min_max.o parallel_min_max.c $(CFLAGS) + +clean : + rm utils.o find_min_max.o parallel_min_max + diff --git a/lab4/src/Summa.c b/lab4/src/Summa.c new file mode 100644 index 000000000..e5801f79a --- /dev/null +++ b/lab4/src/Summa.c @@ -0,0 +1,8 @@ +#include "Summa.h" + +int Sum(const struct SumArgs *args) { + int sum = 0; + for(int i=args->begin;iend;i++) + sum+=*(args->array+i); + return sum; +} \ No newline at end of file diff --git a/lab4/src/Summa.h b/lab4/src/Summa.h new file mode 100644 index 000000000..f89928b8d --- /dev/null +++ b/lab4/src/Summa.h @@ -0,0 +1,8 @@ +struct SumArgs { + int *array; + int begin; + int end; +}; + + +int Sum(const struct SumArgs *args); \ No newline at end of file diff --git a/lab4/src/Summa.o b/lab4/src/Summa.o new file mode 100644 index 000000000..5aaa320c2 Binary files /dev/null and b/lab4/src/Summa.o differ diff --git a/lab4/src/find_min_max.c b/lab4/src/find_min_max.c new file mode 100755 index 000000000..fb1dadc9c --- /dev/null +++ b/lab4/src/find_min_max.c @@ -0,0 +1,20 @@ +#include "find_min_max.h" + +#include + +struct MinMax GetMinMax(int *array, unsigned int begin, unsigned int end) { + struct MinMax min_max; + min_max.min = INT_MAX; + min_max.max = INT_MIN; + + for (unsigned int i = begin; i <= end; i++) { + if (array[i] < min_max.min) { + min_max.min = array[i]; + } + if (array[i] > min_max.max) { + min_max.max = array[i]; + } + } + + return min_max; +} diff --git a/lab4/src/find_min_max.h b/lab4/src/find_min_max.h new file mode 100755 index 000000000..07892028c --- /dev/null +++ b/lab4/src/find_min_max.h @@ -0,0 +1,8 @@ +#ifndef FIND_MIN_MAX_H +#define FIND_MIN_MAX_H + +#include "utils.h" + +struct MinMax GetMinMax(int *array, unsigned int begin, unsigned int end); + +#endif diff --git a/lab4/src/find_min_max.o b/lab4/src/find_min_max.o new file mode 100644 index 000000000..091636729 Binary files /dev/null and b/lab4/src/find_min_max.o differ diff --git a/lab4/src/parallel_min_max b/lab4/src/parallel_min_max new file mode 100755 index 000000000..ddba34ad6 Binary files /dev/null and b/lab4/src/parallel_min_max differ diff --git a/lab4/src/parallel_min_max.c b/lab4/src/parallel_min_max.c new file mode 100755 index 000000000..c28f709f0 --- /dev/null +++ b/lab4/src/parallel_min_max.c @@ -0,0 +1,278 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include "find_min_max.h" +#include "utils.h" + +pid_t child_pid; // Идентификатор дочернего процесса +volatile bool child_exited = false; // Флаг, указывающий на завершение дочернего процесса + +// Обработчик сигнала SIGALRM (вызывается по истечению таймаута) +void alarm_handler(int signum) { + printf("Таймаут истек. Отправляем SIGKILL дочернему процессу...\n"); + kill(child_pid, SIGKILL); // Отправляем сигнал SIGKILL дочернему процессу +} + +int main(int argc, char **argv) { + int seed = -1; + int array_size = -1; + int timeout = -1; + int pnum = -1; + bool with_files = false; + + while (true) { + int current_optind = optind ? optind : 1; + + static struct option options[] = {{"seed", required_argument, 0, 0}, + {"array_size", required_argument, 0, 0}, + {"pnum", required_argument, 0, 0}, + {"by_files", no_argument, 0, 'f'}, + {"timeout", required_argument, 0, 0}, + {0, 0, 0, 0}}; + + int option_index = 0; + int c = getopt_long(argc, argv, "f", options, &option_index); + + if (c == -1) break; + + switch (c) { + case 0: + switch (option_index) { + case 0: + seed = atoi(optarg); + // your code here + // error handling + if (seed <= 0) { + printf("seed is a positive number\n"); + return 1; + } + break; + case 1: + array_size = atoi(optarg); + // your code here + // error handling + if (array_size <= 0) { + printf("array_size is a positive number\n"); + return 1; + } + break; + case 2: + pnum = atoi(optarg); + // your code here + // error handling + if (pnum <= 0) { + printf("pnum is a positive number\n"); + return 1; + } + break; + case 3: + with_files = true; + break; + + case 4: + timeout = atoi(optarg); + if (timeout <= 0){ + printf("timeout must be a positive number\n"); + return 1; + } + break; + + default: + printf("Index %d is out of options\n", option_index); + } + break; + case 'f': + with_files = true; + break; + + case '?': + break; + + default: + printf("getopt returned character code 0%o?\n", c); + } + } + + if (optind < argc) { + printf("Has at least one no option argument\n"); + return 1; + } + + if (seed == -1 || array_size == -1 || pnum == -1) { + printf("Usage: %s --seed \"num\" --array_size \"num\" --pnum \"num\" \n", + argv[0]); + return 1; + } + + // Выделение памяти для массива + int *array = malloc(sizeof(int) * array_size); + // Генерация значений + GenerateArray(array, array_size, seed); + // Инициализация активных дочерних процессов + int active_child_processes = 0; + + struct timeval start_time; + gettimeofday(&start_time, NULL); + + // Создаем каналы синхронизации процессов + int **pipes = malloc(pnum * sizeof(int *)); + for (int i = 0; i < pnum; i++) { + pipes[i] = malloc(2 * sizeof(int)); + } + + for (int i = 0; i < pnum; i++) { + if (pipe(pipes[i]) == -1) { + perror("pipe"); + return 1; + } + } + + if (timeout > 0) { // Если таймаут задан, устанавливаем таймаут с использованием функции alarm + signal(SIGALRM, alarm_handler); // Устанавливаем обработчик сигнала SIGALRM + alarm(timeout); // Устанавливаем таймаут (в секундах) + } + + for (int i = 0; i < pnum; i++) { + pid_t child_pid = fork(); + if (child_pid >= 0) { + // successful fork + active_child_processes += 1; + if (child_pid == 0) { + // child process + + // Определяем размер подмассива + int mini_array_size = array_size / pnum; + int begin = i * mini_array_size; + int end; + + if (i == pnum - 1) { + end = array_size - 1; + } else { + end = (i + 1) * mini_array_size; + } + // parallel somehow + + struct MinMax array_minmax = GetMinMax(array, begin, end); + + + // Создание файлов и запись в них результатов каждого дочернего процесса + if (with_files) { + // use files here + char filename[256]; + snprintf(filename, sizeof(filename), "minmax_%d.txt", i); + + FILE *file = fopen(filename, "w"); + if (file == NULL) { + perror("fopen"); + return 1; + } + + fprintf(file, "%d %d\n", array_minmax.min, array_minmax.max); + + fclose(file); + } else { + // use pipe here + close(pipes[i][0]); // Закрыть чтение из pipe + write(pipes[i][1], &array_minmax, sizeof(struct MinMax)); + close(pipes[i][1]); // Закрыть запись в pipe + } + return 0; + } + + } else { + printf("Fork failed!\n"); + return 1; + } + } + + // Пока есть активные процессы + while (active_child_processes > 0) { + // your code here + int status; + pid_t finished_pid = wait(&status); + + if (finished_pid > 0) { + active_child_processes -= 1; + + if (WIFEXITED(status)) { + int exit_status = WEXITSTATUS(status); + } + } else { + perror("wait"); + return 1; + } + } + + struct MinMax min_max; + min_max.min = INT_MAX; + min_max.max = INT_MIN; + + for (int i = 0; i < pnum; i++) { + int min = INT_MAX; + int max = INT_MIN; + + if (with_files) { + // read from files + char filename[256]; + snprintf(filename, sizeof(filename), "minmax_%d.txt", i); + + // Открытие файла для чтения + FILE *file = fopen(filename, "r"); + if (file == NULL) { + perror("fopen"); + return 1; // Обработка ошибки открытия файла + } + + // Чтение минимума и максимума из файла + int min, max; + fscanf(file, "%d %d", &min, &max); + + // Закрытие файла + fclose(file); + + // Сравнение с глобальным минимумом и максимумом + if (min < min_max.min) min_max.min = min; + if (max > min_max.max) min_max.max = max; + + } else { + // read from pipes + close(pipes[i][1]); // Закрыть запись в pipe + struct MinMax array_minmax; + read(pipes[i][0], &array_minmax, sizeof(struct MinMax)); + close(pipes[i][0]); // Закрыть чтение из pipe + + if (array_minmax.min < min_max.min) min_max.min = array_minmax.min; + if (array_minmax.max > min_max.max) min_max.max = array_minmax.max; + } + + } + + struct timeval finish_time; + gettimeofday(&finish_time, NULL); + + double elapsed_time = (finish_time.tv_sec - start_time.tv_sec) * 1000.0; + elapsed_time += (finish_time.tv_usec - start_time.tv_usec) / 1000.0; + + for (int i = 0; i < pnum; i++) { + free(pipes[i]); + } + free(pipes); + free(array); + + printf("Min: %d\n", min_max.min); + printf("Max: %d\n", min_max.max); + printf("Elapsed time: %fms\n", elapsed_time); + fflush(NULL); + return 0; +} diff --git a/lab4/src/parallel_sum.c b/lab4/src/parallel_sum.c index 66034d2c5..6191c733a 100755 --- a/lab4/src/parallel_sum.c +++ b/lab4/src/parallel_sum.c @@ -1,20 +1,12 @@ #include #include #include - +#include #include +#include +#include "Summa.h" +#include "utils.h" -struct SumArgs { - int *array; - int begin; - int end; -}; - -int Sum(const struct SumArgs *args) { - int sum = 0; - // TODO: your code here - return sum; -} void *ThreadSum(void *args) { struct SumArgs *sum_args = (struct SumArgs *)args; @@ -22,29 +14,74 @@ void *ThreadSum(void *args) { } int main(int argc, char **argv) { - /* - * TODO: - * threads_num by command line arguments - * array_size by command line arguments - * seed by command line arguments - */ - - uint32_t threads_num = 0; - uint32_t array_size = 0; - uint32_t seed = 0; - pthread_t threads[threads_num]; + uint32_t threads_num = -1; + uint32_t array_size = -1; + uint32_t seed = -1; + static struct option options[] = {{"seed", required_argument, 0, 0}, + {"array_size", required_argument, 0, 0}, + {"threads_num", required_argument, 0, 0}, + {0, 0, 0, 0}}; - /* - * TODO: - * your code here - * Generate array here - */ + int option_index = 0; + while(1) + { + int c = getopt_long(argc, argv, "f", options, &option_index); + if (c == -1) break; + switch(c) + { + case 0: + switch(option_index) + { + case 0: + seed = atoi(optarg); + if(seed < 0) + seed = -1; + break; + case 1: + array_size = atoi(optarg); + if(array_size < 1) + array_size = -1; + break; + case 2: + threads_num = atoi(optarg); + if(threads_num < 1) + threads_num = -1; + break; + } + break; + default: + printf("Index %d is out of options\n", option_index); + } + } + if (optind < argc) + { + printf("Has at least one no option argument\n"); + return 1; + } + if (seed == -1 || array_size == -1 || threads_num == -1) + { + printf("Usage: %s --seed \"num\" --array_size \"num\" --threads_num \"num\" \n", argv[0]); + return 1; + } + + pthread_t threads[threads_num]; int *array = malloc(sizeof(int) * array_size); + GenerateArray(array, array_size, seed); + + struct timeval start_time; + gettimeofday(&start_time, NULL); struct SumArgs args[threads_num]; + for(int i = 0; i < threads_num; i++) + { + args[i].array = array; + args[i].begin = i*array_size/threads_num; + args[i].end = (i == (threads_num - 1)) ? array_size : (i+1)*array_size/threads_num; + } for (uint32_t i = 0; i < threads_num; i++) { - if (pthread_create(&threads[i], NULL, ThreadSum, (void *)&args)) { + //Создание нового потока + if (pthread_create(&threads[i], NULL, ThreadSum, (void *)&args[i])) { printf("Error: pthread_create failed!\n"); return 1; } @@ -53,11 +90,19 @@ int main(int argc, char **argv) { int total_sum = 0; for (uint32_t i = 0; i < threads_num; i++) { int sum = 0; + //Завершаем потоки pthread_join(threads[i], (void **)&sum); total_sum += sum; } + struct timeval finish_time; + gettimeofday(&finish_time, NULL); + + double elapsed_time = (finish_time.tv_sec - start_time.tv_sec) * 1000.0; + elapsed_time += (finish_time.tv_usec - start_time.tv_usec) / 1000.0; + free(array); printf("Total: %d\n", total_sum); + printf("Elapsed time: %fms\n", elapsed_time); return 0; } diff --git a/lab4/src/process_memory b/lab4/src/process_memory new file mode 100755 index 000000000..571e0d8f7 Binary files /dev/null and b/lab4/src/process_memory differ diff --git a/lab4/src/psum b/lab4/src/psum new file mode 100755 index 000000000..cee39b7e5 Binary files /dev/null and b/lab4/src/psum differ diff --git a/lab4/src/utils.c b/lab4/src/utils.c new file mode 100755 index 000000000..d1650659d --- /dev/null +++ b/lab4/src/utils.c @@ -0,0 +1,10 @@ +#include "utils.h" + +#include +#include +void GenerateArray(int *array, unsigned int array_size, unsigned int seed) { + srand(seed); + for (int i = 0; i < array_size; i++) { + array[i] = rand(); + } +} diff --git a/lab4/src/utils.h b/lab4/src/utils.h new file mode 100755 index 000000000..f0c6c9456 --- /dev/null +++ b/lab4/src/utils.h @@ -0,0 +1,11 @@ +#ifndef UTILS_H +#define UTILS_H + +struct MinMax { + int min; + int max; +}; + +void GenerateArray(int *array, unsigned int array_size, unsigned int seed); + +#endif diff --git a/lab4/src/utils.o b/lab4/src/utils.o new file mode 100644 index 000000000..53c641244 Binary files /dev/null and b/lab4/src/utils.o differ diff --git a/lab4/src/zombie b/lab4/src/zombie new file mode 100755 index 000000000..133a333ef Binary files /dev/null and b/lab4/src/zombie differ diff --git a/lab4/src/zombie.c b/lab4/src/zombie.c new file mode 100755 index 000000000..13e76d636 --- /dev/null +++ b/lab4/src/zombie.c @@ -0,0 +1,29 @@ +#include +#include +#include +#include +#include + +int main() { + pid_t child_pid = fork(); + + if (child_pid < 0) { + perror("fork"); + exit(1); + } else if (child_pid == 0) { + // Этот код выполняется в дочернем процессе + printf("Дочерний процесс выполняется...\n"); + sleep(2); // Дочерний процесс спит 2 секунды + printf("Дочерний процесс завершается.\n"); + exit(0); + } else { + // Этот код выполняется в родительском процессе + printf("Родительский процесс ожидает завершения дочернего процесса...\n"); + sleep(10); // Родительский процесс спит 10 секунд + //int status; // Переменная для хранения статуса завершившегося дочернего процесса + //wait(&status); // Родительский процесс ожидает завершения дочернего процесса и собирает его статус + printf("Родительский процесс завершается.\n"); + } + + return 0; +} \ No newline at end of file diff --git a/lab5/src/Makefile b/lab5/src/Makefile new file mode 100644 index 000000000..da0388a20 --- /dev/null +++ b/lab5/src/Makefile @@ -0,0 +1,18 @@ +CC=gcc +CFLAGS=-I. +LDFLAGS = -pthread + +mutex: mutex.c + $(CC) -o mutex mutex.c $(LDFLAGS) + +withmutex: withmutex.c + $(CC) -o withmutex withmutex.c $(LDFLAGS) + +factorial_complile: factorial.c + $(CC) -o factorial1 factorial.c $(LDFLAGS) + +factorial: + ./factorial1 -k 10 --pnum 4 --mod 1 + +deadlock: deadlock.c + $(CC) -o deadlock deadlock.c $(LDFLAGS) diff --git a/lab5/src/deadlock b/lab5/src/deadlock new file mode 100755 index 000000000..830908b82 Binary files /dev/null and b/lab5/src/deadlock differ diff --git a/lab5/src/deadlock.c b/lab5/src/deadlock.c new file mode 100644 index 000000000..dbe6027a2 --- /dev/null +++ b/lab5/src/deadlock.c @@ -0,0 +1,50 @@ +#include +#include + +pthread_mutex_t mutex1, mutex2; + +void* thread1(void* arg) { + pthread_mutex_lock(&mutex1); + printf("Thread 1: Holding mutex1...\n"); + sleep(2); // Искусственная задержка для создания deadlock + printf("Thread 1: Waiting for mutex2...\n"); + pthread_mutex_lock(&mutex2); + printf("Thread 1: Got mutex2!\n"); + pthread_mutex_unlock(&mutex2); + pthread_mutex_unlock(&mutex1); + return NULL; +} + +void* thread2(void* arg) { + pthread_mutex_lock(&mutex2); + printf("Thread 2: Holding mutex2...\n"); + sleep(2); // Искусственная задержка для создания deadlock + printf("Thread 2: Waiting for mutex1...\n"); + pthread_mutex_lock(&mutex1); + printf("Thread 2: Got mutex1!\n"); + pthread_mutex_unlock(&mutex1); + pthread_mutex_unlock(&mutex2); + return NULL; +} + +int main() { + pthread_t t1, t2; + + //Инициализируем мьютексы + pthread_mutex_init(&mutex1, NULL); + pthread_mutex_init(&mutex2, NULL); + + //Инициализируем потоки + pthread_create(&t1, NULL, thread1, NULL); + pthread_create(&t2, NULL, thread2, NULL); + + //Ожидаем завершения работы потоков + pthread_join(t1, NULL); + pthread_join(t2, NULL); + + //Уничтожаем мьютексы + pthread_mutex_destroy(&mutex1); + pthread_mutex_destroy(&mutex2); + + return 0; +} \ No newline at end of file diff --git a/lab5/src/factorial.c b/lab5/src/factorial.c new file mode 100644 index 000000000..f68f70b83 --- /dev/null +++ b/lab5/src/factorial.c @@ -0,0 +1,153 @@ +#include +#include +#include +#include +#include +#include +#include + +struct FactArgs { + int begin; + int end; +}; + +int factor = 1; +int modd = 0; +//pthread_mutex_t mutx = PTHREAD_MUTEX_INITIALIZER; +sem_t semaphore; + +void CountPart(void *args) { + //pthread_mutex_lock(&mutx); + sem_wait(&semaphore); + struct FactArgs *arrs = (struct FactArgs *)args; + int num = 1; + for(int i = arrs->begin; i < arrs->end; i++) + { + num = num%modd * i%modd; + } + factor = factor % modd * num % modd; + //pthread_mutex_unlock(&mutx); + sem_post(&semaphore); +} + + +int main(int argc, char **argv) +{ + int k = 0; + int pnum = 0; + + sem_init(&semaphore, 0, 1);//semaphore + + int opt = getopt(argc,argv, "k:"); + if (opt != 'k') + { + printf("Usage: %s -k \"num\" --mod \"num\" --pnum \"num\" \n", argv[0]); + return 1; + } + else + { + k = atoi(optarg); + if (k <= 0) + { + printf("k is a positive number\n"); + return 1; + } + } + + while (true) { + int current_optind = optind ? optind : 1; + + static struct option options[] = {{"mod", required_argument, 0, 0}, + {"pnum", required_argument, 0, 0}, + {0, 0, 0, 0}}; + + int option_index = 0; + int c = getopt_long(argc, argv, "f", options, &option_index); + + if (c == -1) break; + + switch (c) + { + case 0: + switch (option_index) + { + case 0: + modd = atoi(optarg); + if (modd <= 0) + { + printf("mod is a positive number\n"); + return 1; + } + break; + case 1: + pnum = atoi(optarg); + if (pnum <= 0) + { + printf("pnum is a positive number\n"); + return 1; + } + if (pnum > k) + { + printf("pnum must be less or equal to k\n"); + pnum = k; + printf("pnum is equal to k now\n"); + } + break; + + defalut: + printf("Index %d is out of options\n", option_index); + } + break; + + case '?': + break; + + default: + printf("getopt returned character code 0%o?\n", c); + } + } + + if (optind < argc) + { + printf("Has at least one no option argument\n"); + return 1; + } + + if (modd == 0 || pnum == 0) + { + printf("Usage: %s -k \"num\" --mod \"num\" --pnum \"num\" \n", argv[0]); + return 1; + } + + int ars = k/pnum; + int left = k%pnum; + struct FactArgs args[pnum]; + for(int i = 0; i < pnum; i++) + { + args[i].begin = ars*i + (left < i ? left : i) + 1; + args[i].end = ars*(i+1) + (left < i+1 ? left : i+1) + 1; + } + + pthread_t threads[pnum]; + for(int i = 0; i < pnum; i++) + { + if(pthread_create(&threads[i], NULL, (void*)CountPart, (void *)&(args[i])) != 0)//no problem + { + printf("pthread error\n"); + return 1; + } + } + + for(int i = 0; i < pnum; i++) + { + pthread_join(threads[i], NULL); + } + +sem_destroy(&semaphore);// delete + + factor %= modd; + printf("Factorial %d by mod %d = %d\n", k, modd, factor); + + + return 0; +} \ No newline at end of file diff --git a/lab5/src/factorial1 b/lab5/src/factorial1 new file mode 100755 index 000000000..beb6d66fe Binary files /dev/null and b/lab5/src/factorial1 differ diff --git a/lab5/src/mutex b/lab5/src/mutex new file mode 100755 index 000000000..fc086af36 Binary files /dev/null and b/lab5/src/mutex differ diff --git a/lab5/src/mutex.c b/lab5/src/mutex.c index 4e86390db..ef35372dc 100755 --- a/lab5/src/mutex.c +++ b/lab5/src/mutex.c @@ -57,7 +57,7 @@ void do_one_thing(int *pnum_times) { unsigned long k; int work; for (i = 0; i < 50; i++) { - // pthread_mutex_lock(&mut); + //pthread_mutex_lock(&mut); printf("doing one thing\n"); work = *pnum_times; printf("counter = %d\n", work); @@ -82,7 +82,7 @@ void do_another_thing(int *pnum_times) { for (k = 0; k < 500000; k++) ; /* long cycle */ *pnum_times = work; /* write back */ - // pthread_mutex_unlock(&mut); + //pthread_mutex_unlock(&mut); } } diff --git a/lab5/src/withmutex b/lab5/src/withmutex new file mode 100755 index 000000000..497a0c6ee Binary files /dev/null and b/lab5/src/withmutex differ diff --git a/lab5/src/withmutex.c b/lab5/src/withmutex.c new file mode 100644 index 000000000..2cc5d3c97 --- /dev/null +++ b/lab5/src/withmutex.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include + +void do_one_thing(int *); +void do_another_thing(int *); +void do_wrap_up(int); +int common = 0; /* A shared variable for two threads */ +int r1 = 0, r2 = 0, r3 = 0; +pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; + +int main() { + pthread_t thread1, thread2; + + if (pthread_create(&thread1, NULL, (void *)do_one_thing, + (void *)&common) != 0) { + perror("pthread_create"); + exit(1); + } + + if (pthread_create(&thread2, NULL, (void *)do_another_thing, + (void *)&common) != 0) { + perror("pthread_create"); + exit(1); + } + + if (pthread_join(thread1, NULL) != 0) { + perror("pthread_join"); + exit(1); + } + + if (pthread_join(thread2, NULL) != 0) { + perror("pthread_join"); + exit(1); + } + + do_wrap_up(common); + + return 0; +} + +void do_one_thing(int *pnum_times) { + int i, j, x; + unsigned long k; + int work; + for (i = 0; i < 50; i++) { + pthread_mutex_lock(&mut); + printf("doing one thing\n"); + work = *pnum_times; + printf("counter = %d\n", work); + work++; /* increment, but not write */ + for (k = 0; k < 500000; k++) + ; /* long cycle */ + *pnum_times = work; /* write back */ + pthread_mutex_unlock(&mut); + } +} + +void do_another_thing(int *pnum_times) { + int i, j, x; + unsigned long k; + int work; + for (i = 0; i < 50; i++) { + pthread_mutex_lock(&mut); + printf("doing another thing\n"); + work = *pnum_times; + printf("counter = %d\n", work); + work++; /* increment, but not write */ + for (k = 0; k < 500000; k++) + ; /* long cycle */ + *pnum_times = work; /* write back */ + pthread_mutex_unlock(&mut); + } +} + +void do_wrap_up(int counter) { + int total; + printf("All done, counter = %d\n", counter); +} \ No newline at end of file diff --git a/lab6/src/Makefile b/lab6/src/Makefile new file mode 100644 index 000000000..3af3535b9 --- /dev/null +++ b/lab6/src/Makefile @@ -0,0 +1,21 @@ +client : + gcc client.c -o client + +server: + gcc server.c -o server -L. -lpthread -lMultModulo + +run_servers : + ./server --port 20001 --tnum 4 & + ./server --port 20002 --tnum 4 & + +lib : + gcc -c multfact.c -o MultMod.o + ar rcs libMultModulo.a MultMod.o + +stop : + fuser -k 20001/tcp && fuser -k 20002/tcp + +all : client server + +clear : + rm client server \ No newline at end of file diff --git a/lab6/src/MultMod.o b/lab6/src/MultMod.o new file mode 100644 index 000000000..f477b59fb Binary files /dev/null and b/lab6/src/MultMod.o differ diff --git a/lab6/src/client b/lab6/src/client new file mode 100755 index 000000000..da1687646 Binary files /dev/null and b/lab6/src/client differ diff --git a/lab6/src/client.c b/lab6/src/client.c index 91b35af32..71b4457e2 100755 --- a/lab6/src/client.c +++ b/lab6/src/client.c @@ -17,18 +17,7 @@ struct Server { int port; }; -uint64_t MultModulo(uint64_t a, uint64_t b, uint64_t mod) { - uint64_t result = 0; - a = a % mod; - while (b > 0) { - if (b % 2 == 1) - result = (result + a) % mod; - a = (a * 2) % mod; - b /= 2; - } - return result % mod; -} bool ConvertStringToUI64(const char *str, uint64_t *val) { char *end = NULL; @@ -46,9 +35,10 @@ bool ConvertStringToUI64(const char *str, uint64_t *val) { } int main(int argc, char **argv) { + uint64_t ret = 1; uint64_t k = -1; uint64_t mod = -1; - char servers[255] = {'\0'}; // TODO: explain why 255 + char servers[255] = {'\0'}; while (true) { int current_optind = optind ? optind : 1; @@ -69,14 +59,11 @@ int main(int argc, char **argv) { switch (option_index) { case 0: ConvertStringToUI64(optarg, &k); - // TODO: your code here break; case 1: ConvertStringToUI64(optarg, &mod); - // TODO: your code here break; case 2: - // TODO: your code here memcpy(servers, optarg, strlen(optarg)); break; default: @@ -91,28 +78,24 @@ int main(int argc, char **argv) { fprintf(stderr, "getopt returned character code 0%o?\n", c); } } - if (k == -1 || mod == -1 || !strlen(servers)) { fprintf(stderr, "Using: %s --k 1000 --mod 5 --servers /path/to/file\n", argv[0]); - return 1; + return 1;12 } - // TODO: for one server here, rewrite with servers from file - unsigned int servers_num = 1; + unsigned int servers_num = 2; struct Server *to = malloc(sizeof(struct Server) * servers_num); - // TODO: delete this and parallel work between servers to[0].port = 20001; memcpy(to[0].ip, "127.0.0.1", sizeof("127.0.0.1")); - - // TODO: work continiously, rewrite to make parallel + to[1].port = 20002; + memcpy(to[1].ip, "127.0.0.1", sizeof("127.0.0.1")); for (int i = 0; i < servers_num; i++) { struct hostent *hostname = gethostbyname(to[i].ip); if (hostname == NULL) { fprintf(stderr, "gethostbyname failed with %s\n", to[i].ip); exit(1); } - struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(to[i].port); @@ -128,11 +111,8 @@ int main(int argc, char **argv) { fprintf(stderr, "Connection failed\n"); exit(1); } - - // TODO: for one server - // parallel between servers - uint64_t begin = 1; - uint64_t end = k; + uint64_t begin = (k * i) / servers_num; + uint64_t end = (k * (i + 1)) / servers_num; char task[sizeof(uint64_t) * 3]; memcpy(task, &begin, sizeof(uint64_t)); @@ -149,16 +129,16 @@ int main(int argc, char **argv) { fprintf(stderr, "Recieve failed\n"); exit(1); } - - // TODO: from one server - // unite results uint64_t answer = 0; memcpy(&answer, response, sizeof(uint64_t)); - printf("answer: %llu\n", answer); - + if (answer) { + ret = (ret * answer) % 10; + } else { + ret = 1; + } close(sck); } free(to); - + printf("Answer: %llu\n", ret); return 0; -} +} \ No newline at end of file diff --git a/lab6/src/libMultModulo.a b/lab6/src/libMultModulo.a new file mode 100644 index 000000000..c3b2309b9 Binary files /dev/null and b/lab6/src/libMultModulo.a differ diff --git a/lab6/src/multfact.c b/lab6/src/multfact.c new file mode 100644 index 000000000..13dd10282 --- /dev/null +++ b/lab6/src/multfact.c @@ -0,0 +1,13 @@ +#include + +u_int64_t MultModulo(u_int64_t a, u_int64_t b, u_int64_t mod) { + u_int64_t result = 0; + a = a % mod; + while (b > 0) { + if (b % 2 == 1) + result = (result + a) % mod; + a = (a * 2) % mod; + b /= 2; + } + return result % mod; +} \ No newline at end of file diff --git a/lab6/src/server b/lab6/src/server new file mode 100755 index 000000000..c80db99d6 Binary files /dev/null and b/lab6/src/server differ