- 论坛徽章:
- 0
|
写了一个程序,目的是用4个线程同时连接服务器,其中 connect_thread 函数负责连接服务器,
它调用gethostbyname来寻址,如果对 connect _thread 启动4个线程,同时连接服务器,竟然
没有一个线程可以连接成功,但如果不用线程,只调用 connect_thread函数4次,那么每次
调用都可以成功连接到服务器。
为什么多线程连接会失败呢?大家帮我看看啊
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <pthread.h>
void *connect_thread(void *arg); /* 连接服务器 */
int main() {
pthread_t tid[4]; /* 4个线程的ID */
int i;
int clientfd[4]; /* 4次连接到服务器的套接字 */
void *tret;
for (i = 0; i < 4; i++) {
pthread_create(tid+i, NULL, connect_thread, clientfd + i); /* 线程的方式 */
//connect_thread(clientfd + i); /* 函数调用的方式 */
}
}
void *connect_thread(void *arg) {
struct hostent *host = NULL;
struct sockaddr_in addr;
struct sockaddr_in local;
int *clientfd = (int *)arg;
*clientfd = socket( AF_INET, SOCK_STREAM, 0 );
host = gethostbyname( "62.duote.com" ); /* 问题就出在这里,多线程调用这个函数貌似有问题 */
printf("clientfd = %dn", *clientfd); /* 打印此次连接的套接字 */
addr.sin_family = AF_INET;
addr.sin_port = htons( 80 );
addr.sin_addr = *( (struct in_addr *) host->h_addr );
connect( *clientfd, (struct sockaddr *) &addr, sizeof( struct sockaddr_in ));
} |
[ 本帖最后由 kenby 于 2009-4-10 08:13 编辑 ] |
|