linux 线程退出,在启动它的例程返回。

include

include

include

include

include

include

include

include

include

include

include

include

define MAXLINE 64

int Array_Printf(char *data ,int len ,int HexOrDec)
{
int i=0;

if(data == NULL)
{
    return -1;
}
printf("\n----------------------------------------\n");
for(i=0;i<len;i++)
{
    if(HexOrDec==0)
        printf("%02X ",(unsigned char)data[i]);
    else
        printf("%02d ",(unsigned char)data[i]);
}
printf("\n----------------------------------------\n");
return 0;

}

int fd[2];

void Thread_Deal(void *arg){
char line[MAXLINE];
int n,i;
int fd = (int)arg;

while(1)
{
    memset(line,0,sizeof(line));
    n = read(fd, line, MAXLINE);//fd[0]为管道读,默认阻塞
    Array_Printf(line,MAXLINE,0);
    printf("n = %d\n",n);
    sleep(2);    
 }

}

int ret=10;
void Thread_Send(void *arg){
char tem[MAXLINE];
int n,len,i=0;
int fd = (int)arg;

while(1)
{
    if(i++>=10)
    {
        pthread_exit((void*)&ret);
    }
    printf("i = %d\n",i);
    for(n =0; n<64;n++)
    {
        tem[n]=n;
    }  
    len = write(fd,tem,sizeof(tem));
    printf("write len:%d\n",len);      
    sleep(1);    
 }

}

int main(void) {
unsigned char *reg;
if (pipe(fd) < 0)
perror(“pipe error”);
printf(“0: %d,1: %d \n”,fd[0],fd[1]);
int flags = fcntl(fd[0],F_GETFL);
fcntl(fd[0] ,F_SETFL ,flags | O_NONBLOCK);

flags = fcntl(fd[1],F_GETFL); 
fcntl(fd[1] ,F_SETFL ,flags | O_NONBLOCK);

pthread_t thread_pool[2];
pthread_create(&thread_pool[0], NULL, (void*)Thread_Deal, &fd[0]);
pthread_create(&thread_pool[1], NULL, (void*)Thread_Send, &fd[1]);
pthread_join(thread_pool[1], (void *)&reg);
while(1)
{   
    printf("reg = %d \n",*(unsigned char *)reg);
    sleep(1);//100ms
}

}

需要注意pthread_exit((void*)&ret) 参数为全局变量,因为线程函数退出会导致线程栈回收。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值