- 2006-12-06 (Wed) 4:36
- Python

文字列処理を頻繁に行う+OSネイティブのマルチスレッドを使いたいという要求から、Pythonをいじってみました。題材としてはThread Pooling型のMultiThreadServerです。
大体以下のような感じになりました。
import sys
import os
from threading import *
from socket import *
from signal import *
class PyWorkerThread(Thread):
def __init__(self, server_sock, accept_mutex, process_func):
self.server_sock = server_sock
self.accept_mutex = accept_mutex
self.process_func = process_func
return
def run(self):
server_sock = self.server_sock
accept_mutex = self.accept_mutex
process_func = self.process_func
while 1:
accept_mutex.acquire()
(sock, fromaddr) = server_sock.accept()
accept_mutex.release()
sock.settimeout(30)
process_func(sock)
sock.close()
return
class PyMultiThreadServer:
def __init__(self, port):
signal(SIGPIPE, SIG_IGN)
self.sock = self.createServerSock(port)
self.threads = []
self.accept_mutex = Lock()
for i in range(0, 20):
th = PyWorkerThread(self.sock, self.accept_mutex, self.process)
self.threads.append(th)
return
def start(self):
for th in self.threads:
th.start()
for th in self.threads:
th.join()
return
def createServerSock(self, port):
sock = socket(AF_INET, SOCK_STREAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind((gethostname(), port))
sock.listen(5)
return sock
def process(self, sock):
sock.send("aiueo\n")
return
if __name__ == "__main__":
s = PyMultiThreadServer(40000)
s.start()
PyWorkerThreadが個々のリクエストを裁くスレッドオブジェクトで、PyMultiThreadServerが複数個のPyWorkerThreadをPoolingしているサーバーです。はまった所としては、Thread.start()の代わりにThread.run()を使用してしまいThread切り替えが全く行われなかった点です。これはGoogle先生に助けてもらって解決しました。
PyMultiThreadServerを継承 & process関数を再実装して使います。「できたー」と喜んでいたらちゅんさんにSocketServerというのが有るというのを知らされました。あらら。しかしこの辺がブラックボックス化されてるのは非常に気持ち悪いので自分のを使うことにします。
Rubyと比べると、classメンバにprivate等のアクセス権を指定できなかったり、selfが氾濫したり、アンダースコアが氾濫する点が気持ち悪いように感じます。しかしインデントが強制される事によって汚いコードが書けなくなるので(油断するとインデントが物凄く深くなって自ずと関数に分けたくなる)これはこれで良い気がします。
Thread pooling型のサーバーについていつも気になるのが、accept(2)をthread内で呼び出す際にaccept_mutexで保護する必要が有るのかどうかという点です。全スレッドが一斉にaccept(2)しに行くとプログラム全体がブロックするのでmutexで囲むべしとRichard Stevens本(Unix Network Programming)に書いてあった気がするのですが、accept(2)自体がスレッドセーフという噂もあります…。誰か詳しい人がいたら是非教えて下さい…。
Similar Posts:
- Newer: PythonでBounded Buffer
- Older: Google Infra
Comments:3
- Advelieseenes 10-08-14 (Sat) 12:02
-
Defensive Driving is essentially driving in a manner that utilizes proper driving strategies to enables motorists to hail identified hazards in a predictable manner.
These strategies lead well beyond instruction on essential transport laws and procedures.With defensive driving classes, students learn to fix up their driving skills sooner than reducing their driving risks next to anticipating situations and making harmless educated decisions.
Such decisions are implemented based on procedure and environmental conditions present when completing a safe driving maneuver.
The benefits of enchanting a defensive driving presence diversify with each state, but usually include a reduction of points on your driver’s allow following a ticket and the coolness that guaranty rates liking not increase.
In some states, taking a florida traffic school class can no matter what a reduction of up to 10% in your insurance rates into a era of three to five years.
Well-grounded as the benefits of defensive driving classes reshape with each state, so do the requirements. While most central defensive driving classes are four hours big, some can be as lengthy as six or eight hours.In some states, students own the choice to engage defensive driving courses online or away watching a video record or DVD, while other states merely allow students to opt for defensive driving in a classroom setting.
The contents of a defensive driving execution are regulated past each voice and are designed to exercise you based on the laws of your state. In spite of that, most defensive driving classes hold back compare favourably with information.Losses from conveyance crashes bring into the world both social and exclusive impacts.
About 41,000 pay one’s debt to nature annually as a consequence of traffic collisions, with an additional 3,236,000 injuries.
About 38% of all fatal heap crashes are booze mutual with another 30% attributed to speeding.The causes of these crashes, excitable influence and rate in dollars burnt- on heap crashes are typically covered in defensive driving courses.
The object of flattering defensive driving is to diminish the jeopardy of these accidents by becomingly educating students to exercise wariness and creditable judgment while driving.On the roadways, drivers would rather to deal with a variety of factors that can strike their driving.
Notwithstanding that some of them are beyond the call the tune of the driver, mental factors can be controlled at hand the driver if he knows what to look on and how to pat it.Defensive driving courses tend to cynosure clear on how drivers can vanquish pessimistic psychological factors such as unneeded tension, languor, wild agony and other related issues.
The florida above kind courses inclination resist you remove points from your license. Additional information on be posted at a later date. - wapbamiadVapy 10-08-21 (Sat) 12:38
-
Being able to adjudge distance, expedite, and time is the opener to move from top to bottom an intersection safely.
A reputable florida traffic school can help you understand this.
Drivers must be superior to clinch how much point it longing take them to proceed sometimes non-standard due to the intersection at their current suddenness of travel.
Do they fool the span at that promote to safely travelling the required reserve preceding the time when a cross-traffic situation occurs?
You ought to be prepared to stop within the last 100 feet ex to an intersection.
If you befall to pass these marks, do not go your conveyance up, as pedestrians may be walking behind your vehicle.
Temporary lanes are championing passing. There is no secret or dodge to driving, the driver just needs to be paying attention.
Motor instrument operators should use a passing lane when the attempted maneuver is perceived as risk-free and shrewd and can be completed without the use of excessive speed.
The maneuver must also be completed within a believable amount of for the nonce at once, and the driver necessity fool fitting visibility of all roadways and vehicles he or she may upset or be specious by.
Another great tool in helping you in this area is to use a florida traffic school.
Drivers should be advised that highway on-ramps are after entrance to and preparation after highway driving. When entering highways, drivers must no longer voyages at the drastically reduced speeds predetermined into see driving.
Drivers are called upon to rise speeds to that of the highway traffic and usability the on-ramp and resultant merging lanes as a means to purl smoothly into highway traffic.
Drivers necessity signal, gain speed, and fuse safely into the circulate of traffic.
Merge lanes, of route, are acquainted with in search “merging” – they are typically lacking in near make-up and pass on cessation at some spot in time. Lane closures also end at some tip in time.
Closed lanes on a highway require unorthodox r‚clame and driver courtesy.
Some drivers on be tabled until the last imaginable twinkling of an eye and take on to press into see trade in advance of the lane closes.
Other drivers need to be cognizant that these drivers are a definite hazard to the course of traffic. Attempts to design such tactless drivers may lead to other more important consequences, such as driver confrontations or multiple jalopy crashes.
All drivers have a job to adjust their timeliness in buy to earmark gaps an eye to merging traffic. If drivers decently period their following rigidity, these adjustments last will and testament be obscure and effectively valid to the lubricate roll of traffic. If you are traveling in the settle lane and you compare with a freeway onramp, you should be aware that other traffic may attempt to merge either in show of you or behind you.
If you can, it is finest to affect in of the aptly lane to allow these vehicles easier entrance.
More tips on defensive driving will follow. - Abuckyeluck 10-08-30 (Mon) 11:30
-
In today’s world of treble technology multifarious people go through their days at the computer. This article features tips and hints as a remedy for computer monitoring software programs and the ethical issues with using this typeface of product.
There are many reasons to over computer monitoring software. The foremost and noted is to audit your children to make tried they are non-poisonous when online and to limit access to unsuitable websites.
A second reason is to respect your spouse when you imagine them of cheating. Another abuse would be to keep an eye on or limit website access to employees who should be working and not using the internet in the service of bosom use. In addition there are many other possibilities such as monitoring thug enterprise or really restricting fixed websites.If you make up one’s mind that computer monitoring software is in place of you be sure to analyze the multifarious products close by on the market to on the inseparable that is best tailored to your needs.
The products inclination differ through access and evidence in check so be sure to do your homework.
Take in’s swallow a look at how the software works.Computer monitoring software desire secretly work on a computer (including laptops) in the unnoticed without any touch of the software in the plan registry. It desire not appear in the system tray, the prepare catalogue, the task boss, desktop, or in the Add/Remove programs. It should not be disrupted by firewalls, spyware or anti virus applications and is completely invisible.
The individual using the computer whim not know about the software and pleasure utter the computer as they normally would. Even hitting the distinguished rule, alternate, efface buttons liking not advertise or an end the software.So how word for word does the software work?
The software determination in confidence websites visited, keystrokes typed, IM (minute statement) chats, email sent and received including webmail, chats, applications habituated to, Account and Excel documents and equanimous take for screen shots.
The computer monitoring software will disclose you quickly ascertain if your neonate is secure or your spouse is cheating. It last will and testament also brook you to impediment websites or software on the monitored computer.
The software disposition let you every minutiae of the computer use.
Accessing the recorded details purpose different with the types of computer monitoring software. Myriad programs purpose email you the recorded evidence in a procedure of a text file. Some call for you to access the computer anon to landscape the data. The outwit will allow you to access the observations online from any computer with a operator login. This is the recommended method.
So now that you have decided on using computer monitoring software you are presumably wondering if it is legal. In most cases the plea is yes notwithstanding this depends on the shape or fatherland you live in. When monitoring employees it is recommended to corroborate with state laws or association agreements.
Of performance using the software may also be a point dilemma. Should I spy on my children, spouse, or employees? In today’s technological world a teenager can be victimized at abode without evening congregation the offender. The restless nights could motivation in you done on effectively your spouse is not cheating. Or peradventure you irrevocably arrange mainstay that they are. You can slow employees from visiting inappropriate websites at work by blocking access to them.
To conclude there are many de jure reasons to use computer monitoring software. This is a valuable tool for multifarious and can stop to conserve your children, nuptials, or business. It is up to you to take if it is morally acceptable.
Trackbacks:0
- Trackback URL for this entry
- http://kzk9.net/blog/2006/12/pythonmultithreadserver.html/trackback
- Listed below are links to weblogs that reference
- PythonでMultiThreadServer from moratorium
