Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

當以thread來處理socket的問題

0 views
Skip to first unread message

阿瑪迪斯

unread,
Mar 12, 2004, 3:08:11 AM3/12/04
to
於Linux下,我以Multithread來處理I/O multipkexing

不過我遇到一些問題,
若要將socket傳進thread時,應該怎麼處理才是正確的?

有兩種說法:

1.socket必須是以malloc來產生,之後傳address,如:

int *connfdp = malloc(sizeof(int));
*connfdp = accept(listenfd,(SA *)&clientaddr,&clientlen);
pthread_create(&tid, NULL, thread, (void *)connfdp);

這是參考自 http://www.math.umd.edu/~jliu/amsc662/lectures/class28.ppt
的最後幾頁!!

2.socket直接需告傳,之後傳socket address
int connfdp;
connfdp = accept(listenfd,(SA *)&clientaddr,&clientlen);
pthread_create(&tid, NULL, thread, (void *)&connfdp);
這種是一般大家所使用的...

到底何者正確? socket應該只是一個對應到的file dispatcher number
所以兩者都可以嗎~?

但是上述的文件34頁,為何還要提到
what happens if we pass the address of connfd to the thread routine
as in the following code?

謝謝~
--
※ Origin: 楓橋驛站<bbs.cs.nthu.edu.tw> ◆ From: 218-168-220-93.HINET-IP.hinet.net

...

unread,
Mar 12, 2004, 12:00:37 PM3/12/04
to
※ 引述《Amade...@bbs.cs.nthu.edu.tw (阿瑪迪斯)》之銘言:

> 於Linux下,我以Multithread來處理I/O multipkexing
> 不過我遇到一些問題,
> 若要將socket傳進thread時,應該怎麼處理才是正確的?
> 有兩種說法:
> 1.socket必須是以malloc來產生,之後傳address,如:
> int *connfdp = malloc(sizeof(int));
> *connfdp = accept(listenfd,(SA *)&clientaddr,&clientlen);
> pthread_create(&tid, NULL, thread, (void *)connfdp);
> 這是參考自 http://www.math.umd.edu/~jliu/amsc662/lectures/class28.ppt
> 的最後幾頁!!

socket descriptor 只是一個 integer,沒有你說的 malloc 的必要。
你列的文件也沒有這個意思。

> 2.socket直接需告傳,之後傳socket address
> int connfdp;
> connfdp = accept(listenfd,(SA *)&clientaddr,&clientlen);
> pthread_create(&tid, NULL, thread, (void *)&connfdp);
> 這種是一般大家所使用的...
> 到底何者正確? socket應該只是一個對應到的file dispatcher number
> 所以兩者都可以嗎~?
> 但是上述的文件34頁,為何還要提到
> what happens if we pass the address of connfd to the thread routine
> as in the following code?
> 謝謝~

這樣寫基本上沒問題,但前提是,你能完全確定 thread routine 得到
connfdp 的 address 時,這個 pointer 還是有效且指到正確的值?
試想一種情況,你在 main thread 使用一回圈 accept client connection,
然後每 accept 一個 connection 便產生一個 thread 處理。
如果 accept connection 太快,可能 thread routine 被叫起時,
該指標只到的值已經改變了,也就是指到下一個 connection socket。
(因為 connfd 通常是一個 auto variable)
這就是文件所指出要注意的地方。

所以我建議這樣做:

pthread_create(&tid, NULL, thread, (void *) connfd);

在 thread routine 中:

int connfd = (int) arg;

--
Uni\/\/indows | GCS/FA d- s+:- a- C++(+++) UBLS++ P+++(--) L++(+++)>++++@
WW\/\/etworks | W++ N++ w++>+++$ PGP+ tv+ b+(++) G e+++
--
[1;32m※ Origin: [33m交大資工鳳凰城資訊站 [37m<bbs.csie.nctu.edu.tw> [m
[1;31m◆ From: [36m61-230-193-184.HINET-IP.hinet.net [m

0 new messages