ポジローぽけっと

昨日より今日、今日より明日を信じて、トライトライ

第十七回スパルタンプログラミング

何がしたいか?何が問題か?を意識して変なとこでぐだぐだ考えないこと! 30分悩んで分からなかったら、早めにヘルプを出す。

出向先の会社の人の結婚式2次会的なもの(実際は結婚式は挙げてない)に参加。想像してたより楽しかったし、お上さんがノリの良い人でよかった!確実にかかぁ天下。

あと、ハムがうまい、ハムがうまかったわー。しょっぱいけど。

会終了後に電車にゆられ名古屋のいっしーの巣に帰る。帰ると主不在、、、

あんの野郎いつまで先生と飲んでんだ、うらやましい。

アイスの実食べながら、 モダンC言語プログラミング を読んでた。そんな週。

その後、主は好物のサクレを8つ買って帰ってきてた。「買い占めてやろうとおもったけど、やめた」らしい。バカだ。

やりたいこと

先週の懸念点の複数スレッドでaccept可能か確認し、できれば実装したい。

実装できれば、yacc&lexに戻って構文解析をこりこりやりたいな。

確認

Can I call accept() for one socket from several threads simultaneously?に対する回答

Yes, you can call accept() on the same listening socket from multiple threads and multiple process though there might not be as much point to it as you think. The kernel will only allow one to succeed. When this is done with processes it is known as pre-forking and it saves the expense of a fork() for every new connection. But when you are dealing with threads you can more easily have an existing thread pool that waits on a queue of new connections. One thread does the accept and writes the queue and the worker threads read the queue and do their thing. It's cleaner, it's a well understood pattern, and you lose almost nothing.

よく読もうか、僕!

One thread does the accept and writes the quere

じゃん。なので、acceptは1スレッドのみ。

実装へ

Pthread本に学ぶ

  • 複数プロセスの変わりに複数スレッドを洗濯する最大の理由は、複数のスレッド必要とするプログラムと実行に伴うシステムのオーバーヘッドが、複数のプロセスの場合より少ない。オーバーヘッドってなんだ?

  • スレッド間のプロセスリソースの共有は、マルチスレッドプログラミングモデルにおいて、パフォーマンス上の主要な利点の一つであり、同時に「プログラミング的にもっとも難しい局面のひとつである。」

処理の分け方

Pthread本のATMではボス-ワーカ モデルを採用しており、ボススレッドでは「acceptからクライアントからの要求取得まで」を行っている。

参考:atm_svr.c, atm_com_svr_inet.c

1.atm_server_init

//ここからfor

2.server_comm_get_request

2-1.server_comm_init:listenでfdを生成し、FD_SET

//ここからwhile

2-2.selectでFD_SETをチェック

2-3-1.listenのfdがreadyならhandle_new_connection():acceptでfdを生成し、FD_SET

2-3-2.listen以外のfdがreadyならhandle_new_request():既存accept済fdへのクライアントからの要求をread

//ここまでwhile 3-2で要求をreadできたらwhileを抜けて終了

3.pthread_info.num_active++;

4.pthread_create(worker_threadp, NULL, process_request, (void *)workorderp);

5.pthread_detach(*worker_threadp);

//ここからスレッド

4-1.process_request

workorderpからtrans_idを取得し、クライアントからのorderを実施し、回答をresp_bufに書き込む。

4-2.server_comm_send_responseでresp_bufをクライアントに送信。

//ここまでfor

僕が作ろうとしているサーバでは、ボススレッドはacceptまでワーカスレッドは要求取得からをさせる。 となったので、しゃーなろ、書こうか!!

書く!

  • Pthread本の関数の分け方を取り込んだり
  • モダンC言語プログラミング本のC言語でのオブジェクト化を取り込んだり

した。

Pthreadsプログラミング

Pthreadsプログラミング

言葉

  • pre-forking
  • thread pool
  • worker thread which is a well understood pattern:Pthreads本のp.53 のボス/ワーカモデル
  • static variable:http://www48.atwiki.jp/sinmaikeiji/pages/20.html:ヘッダに定義したstatic globalはincludeされた先のファイル内のみで有効なのか?