void write_port(void)
{
int nwrite,i;
for (i=0;i<14;i++)
{
nwrite = write(fd,&ptr[i],2);
usleep(200000);/*每200ms秒发一次数据*/
}
}
void read_port(void)
{
fd_set rd;
int nread,retval;
unsigned char msg[14];
struct timeval timeout;
FD_ZERO(&rd);
FD_SET(fd,&rd);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
retval = select (fd+1,&rd,NULL,NULL,&timeout);/*select 实现i/o复用*/
switch (retval)
{
case 0:
printf("no data input within 1 seconds.\n");
break;
case -1:
perror("select");
break;
default:
if((nread=read(fd,msg,14))>0)
{
printf("nread=%d,msg=%s\n",nread,msg);
}
break;
}
}
void *recv_thread(void )
{
pthread_mutex_lock(&mutex);
read_port();
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void *send_thread(void )
{
pthread_mutex_lock(&mutex);
write_port();
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void create_thread(void )
{
int temp;
memset(thread, 0, sizeof(thread));
if((temp = pthread_create(&thread[0], NULL,(void *)send_thread, NULL)) != 0)
printf("create send_thread failed!\n");
if((temp = pthread_create(&thread[1], NULL,(void *)recv_thread, NULL)) != 0)
printf("create recev_thread failed!\n");
}
void wait_thread(void )
{
if(thread[0] !=0)
{
pthread_join(thread[0],NULL);
printf("send_thread end\n");
}
if(thread[1] !=0)
{
pthread_join(thread[1],NULL);
printf("recev_thread end\n");
}
}
int main(void )
{
int i;
if((fd=open_port(fd,1))<0){
perror("open_port error");
}
if((i=set_port(fd,9600,8,'N',1))<0){
perror("set_opt error");
}
/*用默认属性初始化互斥锁*/
pthread_mutex_init(&mutex,NULL);
int num = 100;
while (num)
{
create_thread();
wait_thread();
num--;
}
pthread_mutex_destroy(&mutex);
close(fd);
return 0;
}