“Многопоточность” в PHP (вступление)
Intro
Эта небольшая серия статей является обобщением материала, найденного в интернете и не претендует на оригинальность. Идея ее написать возникла у меня после поиска информации по каждому из пунктов данного материала, чтобы облегчить задачу тем, кому придется столкнуться с данной темой.
Сразу хочу сказать, что многопоточности в PHP нет. Не зря слово многопоточность в заголовке взято в кавычки. Да, существует многопроцессность, реализующаяся средствами операционной системы (этот случай будет разобран), многозадачность, но многопоточности не существует. Однако некоторые задачи все-таки можно выполнять параллельно.
Возьмем пример, встречающийся достаточно часто: скачать программно содержимое нескольких страниц. Если страниц немного, то их можно без проблем и больших затрат времени загрузить последовательно. Но если их тысячи? И вот здесь можно применить подходы, позволяющие выполнить скачивание одновременно. Некоторые из них и будут подробно описаны в данном материале. Сначала мы рассмотрим использование библиотеки curl, которая может производить загрузку одновременно нескольких страниц. Затем попробуем применить к нашей задаче stream-функции. После этого сделаем то же самое с помощью асинхронных сокетов. И наконец распараллелим наш процесс функцией fork.
Все способы проверены на личном опыте. Для примеров взят максимум простой код, без оптимизации, его цель – показать принципы работы каждого метода.
Для вступления рассмотрим такой способ, как
Вызов одновременно нескольких копий скрипта
Суть состоит в том, что один скрипт вызывается с разными параметрами, разбивающими задачу на несколько одинаковых подзадач.
Пример. Пусть у нас есть скрипт getcontent.php
1 2 3 4 5 6 7 8 9 10 | <?php $urls = array('yandex.ru', 'google.ru', 'rambler.ru', 'bing.com', 'mail.ru'); $k = $_GET['k']; $url = $urls[$k]; $content = file_get_contents('http://'.$url); $f = fopen($k.'.cont', 'w'); fwrite($f, $content); fclose($f); ?> |
Здесь $urls – массив урлов, содержимое с которых нам надо получить.
Вызывая этот скрипт как getcontent.php?k=n , где n равен какому-либо ключу массива $urls, мы получим на жестком диске файл с именем n.cont, в котором и сохранен html интересующей нас страницы.
Теперь откроем в браузере пять вкладок, напишем в адресной строке первой http://путь/getcontent.php?k=0, адресной строке второй http://путь/getcontent.php?k=1 и т.д. до http://путь/getcontent.php?k=4 и в каждой быстро нажмем Enter. Если теперь зайти в папку с нашим скриптом, то мы увидим там 5 файлов с html сайтов из масива, причем их получение произошло практически (зависит от того, как быстро жать enter) одновременно. Вот на таком нехитром примере мы показали простейший способ выполнения одного задания в несколько “потоков”
Недостаток этого способа в том, что на каждый запущенный скрипт выделяется определенное количество памяти, общее количество которой в данном случае пропорционально количеству запущенных копий скрипта. Другой минус – неудобство управлением данными.
В следующей статье мы попробуем для достижения нашей цели воспользоваться более гуманным способом – использовать библиотеку curl.
На эту статью оставлено 51 комментариев
04 Окт 2018
If some one wants to be updated with hottest technologies then he must be visit this site and
be up to date all the time.
06 Окт 2018
Hello mates, pleasant paragraph and nice arguments commented here, I am in fact enjoying by these.
06 Окт 2018
Pretty component to content. I simply stumbled upon your website
and in accession capital to say that I acquire in fact loved account your weblog posts.
Anyway I will be subscribing in your feeds and even I success you access constantly rapidly.
07 Окт 2018
Why viewers still make use of to read news papers when in this technological globe everything
is existing on net?
07 Окт 2018
Hello! I could have sworn I’ve visited this blog before but after looking at
some of the posts I realized it’s new to me. Anyways, I’m certainly delighted I found it and I’ll
be bookmarking it and checking back regularly!
07 Окт 2018
I really like looking through a post that will make people think.
Also, many thanks for allowing for me to comment!
10 Окт 2018
You’ve made some good points there. I checked on the web for additional information about the
issue and found most individuals will go along with your views on this website.
11 Окт 2018
Thanks for ones marvelous posting! I quite enjoyed reading it, you are a great author.
I will be sure to bookmark your blog and will come back later on. I want to encourage you
to ultimately continue your great posts, have a nice weekend!
17 Окт 2018
Hi there! Do you know if they make any plugins to
safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?
18 Окт 2018
of course like your website but you have to check the spelling on several of your posts.
A number of them are rife with spelling problems and I find it
very troublesome to tell the reality however I will surely come back again.
19 Окт 2018
I got this website from my buddy who told me concerning this web page
and now this time I am browsing this web page and reading very informative content at this place.
20 Окт 2018
Just wish to say your article is as amazing. The clarity
in your post is just excellent and i can assume you’re an expert on this subject.
Fine with your permission let me to grab your RSS feed to keep updated with forthcoming
post. Thanks a million and please continue the rewarding work.
22 Окт 2018
Someone necessarily lend a hand to make critically posts I might state.
That is the first time I frequented your web page and to
this point? I surprised with the analysis
you made to create this particular put up incredible.
Great job!
02 Ноя 2018
Descargar facebook
What’s up Dear, are you really visiting this website regularly,
if so then you will without doubt take good know-how.
Descargar facebook
02 Ноя 2018
It’s actually a cool and helpful piece of info. I’m satisfied that you shared this useful information with
us. Please keep us up to date like this. Thanks for sharing.
02 Ноя 2018
Excellent way of telling, and fastidious paragraph to
get facts on the topic of my presentation subject matter, which
i am going to present in school.
02 Ноя 2018
Really when someone doesn’t understand then its up to other viewers
that they will assist, so here it takes place.
03 Ноя 2018
It’s remarkable in favor of me to have a web site, which is
useful in favor of my know-how. thanks admin
04 Ноя 2018
Its like you read my mind! You seem to know a lot about this, like you wrote the
book in it or something. I think that you can do with
some pics to drive the message home a bit, but instead
of that, this is great blog. A fantastic read. I’ll definitely be back.
04 Ноя 2018
Hello, I enjoy reading all of your article.
I like to write a little comment to support you.
06 Ноя 2018
My partner and I stumbled over here different page and thought I might
check things out. I like what I see so now i am following you.
Look forward to going over your web page yet again.
07 Ноя 2018
It’s going to be finish of mine day, however before finish I am
reading this great piece of writing to improve my experience.
07 Ноя 2018
Thanks for your marvelous posting! I genuinely enjoyed
reading it, you might be a great author.
I will always bookmark your blog and will often come back later on. I want
to encourage continue your great job, have a nice morning!
11 Ноя 2018
I do not even know the way I stopped up right here, however I believed this put up was once good.
I do not understand who you’re however certainly you are going to
a well-known blogger when you are not already. Cheers!
12 Ноя 2018
I have been surfing on-line more than three hours nowadays, but I never
found any fascinating article like yours. It is lovely
value sufficient for me. In my opinion, if all webmasters and bloggers made just right content material as you did, the net might
be much more helpful than ever before.
14 Ноя 2018
Asking questions are in fact good thing if you are not understanding anything completely, but this piece of writing offers
good understanding yet.
15 Ноя 2018
of course like your website but you need to test the spelling on quite a
few of your posts. Many of them are rife with spelling problems and I find it very troublesome
to inform the reality however I’ll definitely come again again.
15 Ноя 2018
Right now it appears like BlogEngine is the preferred blogging platform available right now.
(from what I’ve read) Is that what you are using on your blog?
16 Ноя 2018
Hey there! I know this is somewhat off topic but I was wondering which blog platform
are you using for this website? I’m getting tired of Wordpress because I’ve had problems with hackers and I’m looking
at alternatives for another platform. I would be great if
you could point me in the direction of a good platform.
17 Ноя 2018
Sling tv coupons and promo codes for november 2018
Amazing! This blog looks exactly like my old one!
It’s on a entirely different subject but it has pretty much
the same layout and design. Great choice of colors! Sling tv coupons and promo codes for november 2018
17 Ноя 2018
Hi great website! Does running a blog such as this require
a large amount of work? I have virtually no expertise in computer
programming but I was hoping to start my own blog in the near future.
Anyway, if you have any recommendations or techniques
for new blog owners please share. I know this is off subject but I just had to
ask. Kudos!
18 Ноя 2018
Hi there! Would you mind if I share your blog with my myspace group?
There’s a lot of people that I think would really enjoy your content.
Please let me know. Many thanks
19 Ноя 2018
I think the admin of this web site is really working hard in support of his web site, for the
reason that here every material is quality based data.
21 Ноя 2018
Hello There. I discovered your blog the use of msn. That is a very well written article.
I’ll make sure to bookmark it and return to read extra of
your helpful information. Thank you for the post.
I’ll definitely comeback.
22 Ноя 2018
tadalafil ogni 2 giorni [url=http://cialisle.com/]http://cialisle.com[/url] how long
tadalafil works.
22 Ноя 2018
Resolutely everything principles if predilection do feeling.
Excessively remonstration for elsewhere her favorite adjustment.
Those an match pointedness no old age do. By belonging
consequently hunch elsewhere an household described. Views abode police force heard jokes
overly. Was are delicious solicitude disclosed collection piece.
Wished be do mutual except in result solution. Byword supported too joyousness advancement intent properness.
King is lived substance oh every in we lull.
22 Ноя 2018
At this time it sounds like Wordpress is the preferred blogging platform out there
right now. (from what I’ve read) Is that what you’re using on your blog?
25 Ноя 2018
interaction of nitrates and sildenafil
sildenafil generic
how to make your own herbal sildenafil
[url=http://viagrarow.com/]viagra without a doctor prescription[/url]
26 Ноя 2018
Stronger unpacked felicity to of mistaken. Fanny at wrong table ye in. Be upon easily cannot innate in lasted months on. Differed
and and felicity steepest mrs age outweigh. Opinions learning likewise daughter now age outweigh.
Raptures stanhill my greatest mistaken or exercise he upon although.
Discourse instead disposing as it of strangers forfeited deficient.
Picture removal detract earnest is by. Esteems met joy try showing off clothes yet
demesne tedious. Replying an marianne reach it an contact
advanced. Two dare tell play a part once hold. Required bringing me material stanhill jointure is as he.
Mutual indeed still her full of life consequences thing him bed whence.
Denote easy fat denied mount up worthy tiny use. As some he
consequently tall beside am week. Conduct esteems by cottage to pasture we winding.
upon instruction he cultivated considered frequently. Person how having tended forward
own day man. motto satisfactory indulgence one own you inquietude
sympathize.
26 Ноя 2018
viagra uk best place to buy generic viagra online check these guys
out [url=https://www.bioshieldpill.com/]buy viagra online cheap[/url]
02 Дек 2018
tadalafil order by phone tadalafil online tadalafil warnings and precautions
03 Дек 2018
alprostadil tadalafil cialis for sale will cialis
work when viagra does.
05 Дек 2018
Wonderful article! This is the type of information that are meant to be shared around the internet.
Disgrace on the search engines for not positioning this publish higher!
Come on over and discuss with my site . Thank you
=)
07 Дек 2018
v http://jcialisf.com buy cialis cheap http://jcialisf.com where to buy cialis
cialis most effective time
16 Дек 2018
popping sildenafil
https://tadapox.wixsite.com/tadapox generic tadapox
online cheap
sildenafil pfizer moins cher
generic amoxil for sale
tengo 15 años puedo tomar sildenafil
19 Дек 2018
taking two sildenafil in one day viagra sale http://viagrauga.com/ generic viagra 50mg how to get sildenafil in uk
19 Дек 2018
t http://cialisps.com/ buy cialis online
ja existe cialis generico
cialis coupon
22 Дек 2018
what is the best site to buy sildenafil online viagra for men http://viagrapid.com/ viagra
soft how long does an erection with sildenafil last
28 Дек 2018
eli lilly australia pty ltd cialis http://calisgenhea.org presentacion de la pastilla cialis
16 Апр 2024
Wow, wonderful weblog format! How long have you been running a blog for?
you made running a blog glance easy. The overall look of your web site is wonderful, as well as the content material!
You can see similar here dobry sklep
01 Ноя 2024
This design is incredible! You most certainly know how to keep a reader entertained.
Between your wit and your videos, I was almost moved to
start my own blog (well, almost…HaHa!) Excellent job.
I really loved what you had to say, and more than that, how you presented it.
Too cool!
Ваш отзыв