2020-05-25 18:17:49  144088 51

swoole4.4入门安装使用多进程多线程(一)

 标签:   



Swoole 由来

    

       PHP这个语言有很大的局限性,甚至可以说PHP语言只写做Web程序。网络通信框架、异步、多线程,协程,多进程,这些特性正是php所不完善的功能(虽然官方提供很多基础函数可以实现这些功能,PHP语言本身也提供了一些可以实现进行底层操作和网络通信的扩展,比如sockets、libevent、pcntl之类),普通的phper也不具备这些特性的基础认知,基于此 Swoole  应运而生。

      Swoole是韩天峰在2010年底,因为公司业务需要自己实现一个Tcp Socket Server 实现SMTP协议接收数据,但是在当时PHP在这个领域几乎是一片空白,所以自己学习,最终完成了需求;随后便开源了此套系统,希望能帮助其他PHPer解决在这个领域的问题,让PHP从单纯的Web开发扩展到更大的空间。


      Swoole这个名字不是一个英文单词,是由作者创造的一个音近字。最早想到的名字是叫做sword-server,寓意是为广大PHPer创造一把锋利的剑,后来联想到google也是凭空创造出来的,所以我就给它命名为swoole。

swoole 介绍

 

       Swoole是一个完全使用C语言编写面向生产环境的 PHP 异步网络通信引擎,使 PHP 开发人员可以编写高性能的异步并发 TCP、UDP、Unix Socket、HTTP,WebSocket 服务。Swoole 可以广泛应用于互联网、移动通信、企业软件、云计算、网络游戏、物联网(IOT)、车联网、智能家居等领域。 使用 PHP + Swoole 作为网络通信框架,可以使企业 IT 研发团队的效率大大提升,更加专注于开发创新产品。

Swoole特性


PHP的 协程 高性能网络通信引擎,使用C/C++语言编写php扩展,提供了多种通信协议的网络服务器和客户端模块。包括:

    TCP/UDP/UnixSock 服务器端
    Http/WebSocket/Http2.0 服务器端
    协程 TCP/UDP/UnixSock
    协程 MySQL
    协程 Redis
    协程 Http/WebSocket
    协程 Http2
    AsyncTask
    毫秒定时器
    协程文件读写
异步 文件读写  异步mysql  redis


Swoole版本


Swoole2.0 支持了类似 Go 语言的协程    不完美   

3 版本协程 存在兼容问题 放弃

Swoole4支持完整的协程编程模式,可以使用完全同步的代码实现异步程序。

PHP代码无需额外增加任何关键词,底层自动进行协程调度,实现异步IO。
Swoole4协程仅支持PHP7,无法在PHP5中使用

异步回调模块已过时,目前仅修复 BUG,不再进行维护, 且在4.3版本中移除了异步模块。请使用 Coroutine 协程模块。
仅支持 Linux、FreeBSD、MacOS 三种操作系统

在Windows平台,可使用CygWin或WSL(Windows Subsystem for Linux)

目前cygwin版本为测试版本,Windows 下Swoole的功能受限。


swoole案例:https://wiki.swoole.com/wiki/page/p-case.html

workerman   swoole区别

 
workerman纯php    swoole C/C++语言编写 作为php的扩展

workerman 多进程      swoole   协程   多进程  多线程

swoole性能优于workerman

workerman   win/linux     swoole  win测试  线上linux

swoole并没有用libevent,所以不需要安装libevent

swoole并不依赖php的stream/sockets/pcntl/posix/sysvmsg等扩展


swoole安装环境


centos 7.6
php  7.2       //   lnmp 一键安装
swoole   4.4.3

建议使用 Ubuntu14、CentOS7 或更高版本的操作系统

Swoole-1.x需要 PHP-5.3.10 或更高版本

Swoole-4.x需要 PHP-7.0.0 或更高版本

单数版本为特性新增版本,主要工作是新增功能特性、代码重构、结构调整。可能会带来一些BUG

双数版本为问题修复版本,主要工作是修复现有的已知问题、提升性能、完善细节。稳定性更高


swoole安装方式


第一种

--enable-swoole    编译 php直接编译进去

第二种

pecl  install   swoole

第三种

docker   安装

第四种(推荐)

下载 :http://pecl.php.net/package/swoole

/usr/local/php/bin/phpize

./configure --with-php-config=/usr/local/php/bin/php-config   --enable-openssl  --enable-http2  --enable-sockets  --enable-mysqlnd

编译参数 : https://wiki.swoole.com/wiki/page/437.html

make  && make install

extension = swoole.so

php   -m   或者 phpinfo()  

php  --ri  swoole


Swoole的绝大部分功能只能用于cli命令行环境,请首先准备好Linux Shell环境。


进程和线程


      进程是一个具有一定独立功能的程序在一个数据集上的一次动态执行的过程,是操作系统进行资源分配和调度的一个独立单位,是应用程序运行的载体。

     线程是程序执行中一个单一的顺序控制流程,是程序执行流的最小单元,是处理器调度和分派的基本单位。一个进程可以有一个或多个线程。

1. 线程是程序执行的最小单位,而进程是操作系统分配资源的最小单位;

2. 一个进程由一个或多个线程组成,线程是一个进程中代码的不同执行路线

3. 进程之间相互独立,但同一进程下的各个线程之间共享程序的内存空间(包括代码段,数据集,堆等)及一些进程级的资源(如打开文件和信号等),某进程内的线程在其他进程不可见;

4. 调度和切换:线程上下文切换比进程上下文切换要快得多

5  线程天生的共享内存空间,线程间的通信更简单,避免了进程IPC引入新的复杂度。

进程开销大    线程开销小

php实现多进程


pcntl是php官方的多进程扩展,只能在linux环境使用   --enable-pcntl

pcntl_fork — 在当前进程当前位置产生分支(子进程)

fork是创建了一个子进程,父进程和子进程 都从fork的位置开始向下继续执行,不同的是父进程执行过程中,得到的fork返回值为子进程 号,而子进程得到的是0。

   $pid = pcntl_fork();
    if($pid==0){
        echo '我是子进程 id:'.getmypid().PHP_EOL;
    }else{
        echo  '我也是子进程 '.$pid;
    }


进程间的通信


在各个进程中,内存空间都是不一致的,各个变量都是在不同的内存空间

    $str = 'lampol';
    $pid = pcntl_fork();
    if($pid>0){
        $str.='111111';
        echo $str.PHP_EOL;  //lampol111111
    }else{
        echo  $str;  //lampol
    }


进程间空间独立  数据不能共享


管道通信

消息队列通信

进程信号通信

共享内存通信,映射一段能被其他进程所访问的内存,这段共享内存由一个进程创建,但多个进程都可以访问。共享内存是最快的 IPC(进程间通信) 方式,它是针对其他进程间通信方式运行效率低而专门设计的。它往往与其他通信机制,如信号量,配合使用,来实现进程间的同步和通信。

套接字通信

第三方通信,使用文件操作,mysql,redis等方法也可实现通信

多线程


PHP 默认并不支持多线程,要使用多线程需要安装 pthread 扩展,而要安装 pthread 扩展,必须使用 --enable-maintainer-zts 参数重新编译 PHP,这个参数是指定编译 PHP 时使用线程安全方式。

下载pthreads


wget http://pecl.php.net/get/pthreads-3.1.6.tgz
 /usr/local/php/bin/phpize
 ./configure    --with-php-config=/usr/local/php/bin/php-config
extension =pthreads.so


线程安全


多线程是让程序变得不安分的一个因素,在使用多线程之前,首先要考虑线程安全问题:

线程安全:线程安全是编程中的术语,指某个函数、函数库在多线程环境中被调用时,能够正确地处理多个线程之间的共享变量,使程序功能正确完成。


PHP 实现的线程安全主要是使用 TSRM 机制对 全局变量和静态变量进行了隔离,将全局变量和静态变量 给每个线程都复制了一份,各线程使用的都是主线程的一个备份,从而避免了变量冲突,也就不会出现线程安全问题。


本文档对应的视频教程:https://ke.qq.com/course/432680?tuin=30289dc0


欢迎加入workerman/swool技术交流群:604438441


51 条留言

  1. 匿名用户

    Wow! After alll I got a weblog from whwre I be able to genuinely obtain useful information regarding mmy study and knowledge. https://sergeirzd5kydip.medium.com/career-goals-essay-96fe2504191a essay writing websites essay writing websites https://tiomonar.medium.com/heroes-essay-examples-882d63f54c94 https://sergeirzd5kydip.medium.com/career-goals-essay-96fe2504191a

  2. 匿名用户

    Wow! After all I got a webog from where I be able to genuinely obtajn useful information regarding my study and knowledge. https://sergeirzd5kydip.medium.com/career-goals-essay-96fe2504191a essay writing websites essay writing websites https://tiomonar.medium.com/heroes-essay-examples-882d63f54c94 https://ignatiusy8g1uuy.medium.com/life-story-essay-3a264a748c29

  3. 匿名用户

    Piece of writting writiung is also a excitement, if you know after that you can write or else it is complicated tto write. https://clients1.google.com.tj/url?q=https://www.otzyvru.com/plasticheskiy-hirurg-maksim-ivanchuk максим иванчук пластический хирург киев максим иванчук пластический хирург киев https://clients1.google.com.kw/url?q=https://barb.ua/vishnevoe/master/maksim-ivanchyk/comments

  4. 匿名用户

    certainly like your web site but you need to chek the spelling on quite a feew off your posts. A number of them are rife with spelling issues and I inn finding it verry bothersome to inform the truth then again I'll certainly come again again. https://nr2.com.ua/zdorove/2020/05/29/ivanchuk-maksim-otzyvy-hirurga-o-tipah-rinoplastiki/ иванчук хирург отзывы иванчук хирург отзывы https://www.medcentre.com.ua/vrachi/ivanchuk-maksim-sergeevich.html

  5. 匿名用户

    This text is priceless. When can I find out more? https://www.medcentre.com.ua/vrachi/ivanchuk-maksim-sergeevich.html максим иванчук отзывы максим иванчук отзывы https://www.medcentre.com.ua/vrachi/ivanchuk-maksim-sergeevich.html

  6. 匿名用户

    This text is priceless. When can I find out more? https://www.medcentre.com.ua/vrachi/ivanchuk-maksim-sergeevich.html максим иванчук отзывы максим иванчук отзывы https://barb.ua/vishnevoe/master/maksim-ivanchyk/comments

  7. 匿名用户

    Everyone loves what you guys are usually up too. This kind of clever work and exposure! Keep up the very good works guys I've you guyys to blogroll. https://termpaperwriterservice.com write my custom paper write my custom paper https://termpaperwriterservice.com

  8. 匿名用户

    Hi there too every one, the contents present at this weeb site are genuinely remarkable for people experience, well, eep up the good work fellows. https://writinganessay.info best essay writing service in usa best essay writing service inn usa https://writinganessay.info https://writinganessay.info

  9. 匿名用户

    Hi there to every one, the contents present at this web site are genuinely remarkable for peopl experience, well, keep up the good work fellows. https://writinganessay.info best essay writing service in usa best essay writing servioce in usa https://writinganessay.info https://writinganessay.info

  10. 匿名用户

    Someone necessarily asdist to make seriously posts I might state. Thaat is the very first time I frequented yourr website page and so far? I surprised with the research you made to create this particular put up amazing. Great task! https://writemyessaybest.com essay writing service essay writting service https://writemyessaybest.com/

  11. 匿名用户

    Touche. Great arguments. Keep up the good work. https://writinganessay.info research papers research papers https://bestessaywritingservice.info https://writinganessay.info

  12. 匿名用户

    Touche. Great arguments. Keep up the gopod work. https://writinganessay.info research papers research papers https://bestessaywritingservice.info https://persuasiveessays.info

  13. 匿名用户

    You can certainly see your eexpertise within the article you write. The arena hopes for more passionate writers such as yoou who are not afraid to say how they believe. Always follow your heart. https://medium.com/@wrightqewrgv3a/opinion-essay-cbf6473065dd essay help websites essay help websites https://itnias.medium.com/the-story-of-an-hour-literary-analysis-essay-dd8292911e8 https://rebalful.medium.com/common-app-essay-word-limit-c8818e62aa49

  14. 匿名用户

    Thank you, I've just been searching for info about this subject for a while and yours is the best I've came upon sso far. However,what in regards to thhe bottom line? Are you certain concerning the source? https://servicethesis.com business essay writing service business essay writing service https://servicethesis.com

  15. 匿名用户

    Hi there mates, pleasant post and nice arguments commented here, I am genuinely enjoying byy these. https://clausejnlrtf.medium.com/texas-college-essay-prompts-53b80a0f4150 essay writing service reddit essay writing service reddit https://cyrusvt4xmoi3d.medium.com/child-neglect-essay-4d3132cfd79b https://chef24su0kuw.medium.com/essay-about-drugs-86d5f12c71d

  16. 匿名用户

    I think the admiun of this site is genuinely working hard in support of his web page, since here every material is quality based information. https://essayhelpforall.com/ scholarshipessay writing service https://essayhelpforall.com/ https://essayhelpforall.com/

  17. 匿名用户

    I think the admin of this site is genuinely working hafd in support of his web page, since here every material is quality based information. https://essayhelpforall.com/ scholarship essay writing service https://essayhelpforall.com/ https://essayhelpforall.com/

  18. 匿名用户

    Ahaa, its pleasaznt dialogue concerning this article at this place at this web site, I have read all that, so at this time me also commenting at this place. https://essaypaperwritingservice.com wrie my paper affordable write my paper affordable https://essaypaperwritingservice.com

  19. 匿名用户

    WOW just what I was looking for. Came hede by searching for writing annd essay https://orderessayusukau.com online writing paper online writing paper https://orderessayusukau.com

  20. 匿名用户

    Great post. I was checking constantly thos blog and I'm impressed! Extremely helpful information specially the last part :) I care for such information a lot. I was sseeking this certain info for a long time. Thank you and best of luck. https://termpaperwriterservice.com essay writing services cheap essay writing services cheap https://termpaperwriterservice.com

  21. 匿名用户

    Hi it's me, I am also visiting this web site daily, this web page is really njce and the people are in fact sharing fastidious thoughts. https://writemyessaybest.com paper writing website paper writing website https://writemyessaybest.com

  22. 匿名用户

    Thanks for your marvelous posting! I actually enjoyed reading it, you are a great author.I will always bookmark your blog and will often come back later on. I want to encourage one to continue your great job, have a nice afternoon! click site click site https://vietnam-money.com https://movpicture.com

  23. 匿名用户

    As the admun of this websie is working, nno question very shortly it will be well-known, due to iits quality contents. https://collegeapplicationessaywritingservice.info essay writers essay writers https://collegeapplicationessaywritingservice.info https://collegeapplicationessaywritingservice.info

  24. 匿名用户

    Write more, thats all I have to say. Literally, it seems as though you relied oon the video to make your point. You definitely know what youhre talking about, wwhy waste your intelligence on just posting videos to your site when you could be giving us something enlightening to read? https://pechatnick.com/articles/gde-naiti-kyrsi-po-obycheniu-prodyktam-microsoft?&utm_source=search Интернет сайт https://pechatnick.com/articles/gde-naiti-kyrsi-po-obycheniu-prodyktam-microsoft?&utm_source=search

  25. 匿名用户

    My brother recommended I might like this blog. He was totally right. This post truly made myy day. You can not imagine just how much time I had spent for this information! Thanks! https://helpwriting.info cheap essay writing service cheap essay writing service https://helpwriting.info https://helpwriting.info

  26. 匿名用户

    My brother recommended I might like this blog. He was totally right. Thhis post truly made my day. You can nott imagine just how much time I had spent for this information! Thanks! https://helpwriting.info cheap essay writing service cheap esway writing service https://helpwriting.info https://helpwriting.info

  27. 匿名用户

    consyantly i used to read smaller articles which as well clear their motive, and thjat is also happening with this post which I am reading now. https://termpaperwriterservice.com/ write a paper for me write a paper for me https://termpaperwriterservice.com/

  28. 匿名用户

    Hi there this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors orr if you have to manualky code with HTML. I'm starting a blog soon but have no coding knowledge so I wanted to get advice from someone with experience. Any help woild be greatly appreciated! https://orderessayusukau.com writing aan arguumentative essay writing an argumentative essay https://orderessayusukau.com/

  29. 匿名用户

    you are really a excellent webmaster. The site loading pace is amazing. It sort of feels that you're doing any unique trick. Furthermore, The contents are masterwork. you have done a wonderful job on this subject! https://australianessaywritingservice.info buy essay papers buy essay papers00000039 https://writingmypaper.info https://writeessaysforme.info

  30. 匿名用户

    What's up mates, pleasant paragraph and good urging commented here, I am genuinely enjoyimg by these. https://bestessaywritingservice.info/thesis-writing-services-uk.html cheap essay writing service usa https://bestessaywritingservice.info/writing-a-good-conclusion-for-a-research-paper.html

  31. 匿名用户

    I want to to thank you for this excellent read!! I certainly loved everyy little bit of it. I have you saved as a favorite to check out new stuff you post… https://collegeapplicationessaywritingservice.info/anxiety-disorder-literature-review-essay.html paper writing services paper writing services https://collegeapplicationessaywritingservice.info/

  32. 匿名用户

    Hey There. I found your blog using msn. This is a really well written article. I will maake sure to bookmark it and come back to read more of your ussful information. Thank for the post. I'll certainly return. https://helpassignmentwritingservice.info/biodiesel-research-papers.html essay help websites essay help websites https://helpassignmentwritingservice.info/bad-academic-writing-examples.html

  33. 匿名用户

    When I initially left a comment I seem to have clicked the -Notify me when new comments are added- checkbbox and now each time a cojment is added I receive 4 emails with the same comment. There has to be a way you are able to remove me from that service?Many thanks! https://australianessaywritingservice.info/ dissertation writers uk dissertation writers uk https://australianessaywritingservice.info/

  34. 匿名用户

    Good post. I learn something new and challenging on blogs I stumbleupon everyday. It's always helpful to read through articles from other writers and practice a little something from their websites. https://onlineessayforyou.com/ english essay writing service affordable essaysaffordable essays https://onlineessayforyou.com/ https://onlineessayforyou.com/ https://onlineessayforyou.com/

  35. 匿名用户

    If you desire to get a good deal from thks piece of writing then you have to apply these methods tto yokur won weblog. https://www.retail.ru/forum/?PAGE_NAME=message&FID=12&TID=14415&TITLE_SEO=14415-courses&MID=60649&tags=&q=%D0%BA%D1%83%D1%80%D1%81%D1%8B&FORUM_ID%5B0%5D=0&DATE_CHANGE=0&order=relevance&s=%D0%9D%D0%B0%D0%B9%D1%82%D0%B8&result=reply посетите следующую веб-страницу https://www.retail.ru/forum/?PAGE_NAME=message&FID=12&TID=14415&TITLE_SEO=14415-courses&MID=60649&tags=&q=%D0%BA%D1%83%D1%80%D1%81%D1%8B&FORUM_ID%5B0%5D=0&DATE_CHANGE=0&order=relevance&s=%D0%9D%D0%B0%D0%B9%D1%82%D0%B8&result=reply

  36. 匿名用户

    Write more, thats all I hav to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why throw awazy your intelligence on just posting videos to your site when you could be giving us something enlightening to read? https://buyessayonlinecheap.info write my essay for me write my essay for me https://buyessayonlinecheap.info

  37. 匿名用户

    I'm extremely inspired together with your writing skills and also with the format for your weblog. Is this a paid topic or did you customize it your self? Either way stay up the excellent quality writing, it's rare to see a nice weblog like this one these days.. https://essayhelpforall.com/ best custom writing best custom writing https://essayhelpforall.com/

  38. 匿名用户

    If some one desires expert view concerning blogging then i advise him/her to go to see this webpage, Keep up the pleasant work. https://essaywritingtld.com/ essay writing service toronto essay writing service toronto https://essaywritingtld.com/

  39. 匿名用户

    Hi this is kinda oof off topic but I was wanting to know if blogs usse WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding expertise so I wanted too get advvice from sommeone with experience. Any help would be greatly appreciated! https://essaywritingaboutmother660.blogspot.com/2020/10/university-of-wisconsin-essay.html professional essay writing service professional essay writing service https://bestcustomessaywriting293.blogspot.com/

  40. 匿名用户

    I'm not sure why but thiss weblog is loading incredibly slow for me. Is anyone else having this issue or is it a problem on my end? I'll check back later on aand see if the problem still exists. http://tululu.org/forum/viewtopic.php?f=13&t=14097&p=191082

  41. 匿名用户

    I am regular reader, how are you everybody? This paragraph posted at thi site is actually nice. https://researchpaperorder.com college admiission essay writing service college admissioln essay writing service https://admissionessaywritingservice.com

  42. 匿名用户

    obviously likke your website however you have to check the spelling on quite a few of your posts. Several of them are rife with spelling issues and I find iit very bothersome too inform the truth howevesr I'll surely come back again. https://admissionessaywritingservice.com best online essay writing service best online essay writing service https://admissionessaywritingservice.com

  43. 匿名用户

    I am regular visitor, hoow are you everybody? This piece oof writing posted at thus web page iis genuinely fastidious. https://admissionessaywritingservice.com essay writing essay writing https://admissionessaywritingservice.com

  44. 匿名用户

    Hey this is kinda oof off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding skills so I wanted to get guidance from someone with experience. Any help would be greatly appreciated! https://writeanessayforme.info write essays write essays https://writeanessayforme.info

  45. 匿名用户

    Hi, I woukd like to subscribe for this webpage to take hottest updates, therefore where can i do it please assist. https://bookreviews631.blogspot.com/2020/10/buying-research-papers.html writing papers writing papers https://howtowritethebestessayever490.blogspot.com/2020/10/usda-forest-service-research-paper-pnw.html

  46. 匿名用户

    Your mode of explaining all in this piece of writing is genuinely nice, every one be capable of effortlessly be aware of it, Thhanks a lot. https://letterboxd.com/ojowosite/ посетите ваш URL

  47. 匿名用户

    Great weblog here! Also yoiur site so much up fast! What host are you the usage of? Can I aam gettng your associate ink for your host? I want my website loafed up as quickly as yours lol http://vrn.best-city.ru/forum/thread539984053/ посмотреть здесь

  48. 匿名用户

    Oh my goodness! Awesome article dude! Thank you, However I amm going through trohbles with your RSS. I don't understand the reason whyy I can't join it. Is there anybody else getting similar RSS problems? Anyone that knows the answe will you kindly respond? Thanks!! https://writingmypaper.info last minute essay writing service last minute essay writing service https://writingmypaper.info

  49. 匿名用户

    Hi, Neat post. There is an issue along with your web site in internet explorer, might test this? IE still is the marketplace leader and a large component of folks will miss your excellent writing due tto thjis problem. https://essaywritingservicereddit.info/ research paper writing research paper writing https://essaywritingservicereddit.info/how-do-you-start-a-synthesis-essay.html

  50. 匿名用户

    Very rapidly this web page will be famous among all blogging and site-building people, due to it's fastidious articles or reviews https://buycustomessay.info buy essay online reviews buy essay online reviewsThanks for consisting of the beautiful pictures-- so vulnerable to a sense of reflection. https://persuasiveessays. https://buycustomessay.info

  51. 匿名用户

    Everything said was very logical. However, what about this? what if you typed a catchier post title? I am not saying your content is not good., however suppose you added something that grabbed a person's attention? I mean linux运维架构--PHP开发-零基础学习PHP视频教程 is a little vanilla. You might peek at Yahoo's home page and note how they create post headlines to grab people to click. You might add a video or a related pic or two to get readers interested about everything've written. In my opinion, it could bring your website a little bit more interesting. https://comprarcialis5mgonline.com/marca-cialis-professional-20-mg.html best online pharmacy for generic cialis

给我留言

评论内容