Chinaunix首页 | 论坛 | 博客
  • 博客访问: 71881
  • 博文数量: 28
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 291
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-29 14:47
文章存档

2014年(13)

2013年(15)

我的朋友

分类: 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

阅读(987) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~