分类: C/C++
2013-12-12 14:39:12
#include "common.h"
#define MAX_LINE 100
int THREAD_NUM=100;
struct sockaddr_in sin;
pthread_mutex_t mutex;
static int count=0;
void sock_init();
void my_read(int fd);
void my_write(int fd,char *buf);
void* thfn(void* arg);
int main(int argc,char *argv[])
{
char str[30];
int i;
int err;
pthread_t tid[THREAD_NUM];
if(argc>1)
THREAD_NUM=atoi(argv[1]);
sock_init();
pthread_mutex_init(&mutex,NULL);
for(i=0;i
sprintf(str,"this is %d threading",i);
if((err=pthread_create(&tid[i],NULL,thfn,(void*)str))!=0)
{
printf("tid[%d] create failed\n",i);
exit(1);
}
}
for(i=0;i
printf("tid [%d] is: 0x%x\n",i,tid[i]);
pthread_join(tid[i],NULL);
}
printf("me send thread_num[%d]\n",THREAD_NUM);
exit(0);
}
void* thfn(void* arg)
{
char *str=(char*)arg;
int sfd;
pthread_mutex_lock(&mutex);
if((sfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("fail to creat socket");
exit(1);
}
connect(sfd,(struct sockaddr*)&sin,sizeof(struct sockaddr));
my_write(sfd,str);
my_read(sfd);
close(sfd);
pthread_mutex_unlock(&mutex);
sleep(1);
return NULL;
}
void my_read(int fd)
{
char buf[MAX_LINE];
read(fd,buf,MAX_LINE);
printf("%d recive from server: %s\n",count,buf);
}
void my_write(int fd,char *buf)
{
char str[100];
count++;
printf("%d send from client: %s\n",count,buf);
sprintf(str,"%d senf from client: %s\n",count,buf);
write(fd,str,strlen(str)+1);
}
void sock_init()
{
bzero(&sin,sizeof(struct sockaddr_in));
sin.sin_family=AF_INET;
inet_pton(AF_INET,"130.234.1.110",&sin.sin_addr);
sin.sin_port=htons(SERVER_PORT);
}结果:没有达到预期的效果,不知道原因出在哪里了。应该是从0开始到9结束
send from client: this is 9 threading
recive from server: this is server
send from client: this is 9 threading
recive from server: this is server
send from client: this is 9 threading
recive from server: this is server
send from client: this is 9 threading
recive from server: this is server
send from client: this is 9 threading
recive from server: this is server
send from client: this is 9 threading
recive from server: this is server
send from client: this is 9 threading
recive from server: this is server
send from client: this is 9 threading
recive from server: this is server
send from client: this is 9 threading
recive from server: this is server
send from client: this is 9 threading
recive from server: this is server