Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

sockets - How does poll() work and how is it different from multiple threads?

I am completely new to OS and networking. I am unable to find a good resource (like Beejs' guide) to grasp these concepts. I want to make a TCP server that can handle multiple connections. poll() allows me to directly do it (as given in Beej's guide). So why do multithreading and multiprocessing? What is the difference between these three and when to use which?

PS: I have little experience with the OS.

question from:https://stackoverflow.com/questions/65649957/how-does-poll-work-and-how-is-it-different-from-multiple-threads

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Chris Dodd summarized "you use whatever technique is appropriate for the problem you are trying to solve". But to give little context I would like to quote few general considerations to pick a multi threaded / process approach.

When you are not intending to do either of the things, still you are having a single thread in execution where you are performing polling operations. That sever might with stand low to moderate traffic but lets suppose you are receiving more and more requests, entire load is fell on single thread while there is possibility to offload work to idle threads (threads in cpu context). So this opens up a path to multi threaded/process approach.

By creating a new thread (in the process) you are creating a new execution flow which runs in parallel to all the earlier (created) threads. The advantages of picking new threads over process is all the threads share same heap and global memory making inter thread communication easy. Loosely speaking you want to pick thread approach when you just want to run the same code snippet to serve all the clients.

But lets suppose each request you are serving requires running all together a different program and there is no complex communication between parent and child process you are better off creating a new process.

To conclude you might come across a scenario where the main process does pooling and it spawns few child process and child process creates multiple threads thus using all the three things at once. So pick the thing that best suits for the purpose.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...