Linux 线程编程3.0

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int g_i = 10;
struct stu
{
    int id;
    char name[32];
};

void *fun(void *arg)
{
    int i = 0;
    g_i = 20;
    struct stu *ps;

    ps = (struct stu*) arg;

    printf("stu:%d %s\n",ps->id,ps->name);

    int *p = malloc(sizeof(int));
    printf("malloc p = %p\n",p);

    *p = 20;

    while(1)
    {
        sleep(1);

        if(i>10)
        {
            printf("pthread of main  exit...\n");
            pthread_exit(p);//结束并返回p指针
        }

        i++;
        printf("fun run..\n");
    }
    return NULL;
}


int main()
{
    int ret;
    pthread_t  pth_id;
    int i = 0;
    int *p;
    struct stu *ps;

    ps = malloc(sizeof(struct stu));
    ps->id = 20;
    strcpy(ps->name,"zhangsan");

    ret = pthread_create(&pth_id,NULL,fun,(void *)ps);
    if(ret<0)
    {
        perror("pthread");
    }
    printf("pthread create over..\n");

    printf("pthread join\n");

    pthread_join(pth_id,(void **)&p);//接收子线程返回指针
    printf("p = %p *p = %d\n",p,*p);
    printf("pthread join over..\n");

    free(p);
}

结果如下:

pthread create over..
pthread join
stu:20 zhangsan
malloc p = 0x7f604c0008c0
fun run..
fun run..
fun run..
fun run..
fun run..
fun run..
fun run..
fun run..
fun run..
fun run..
fun run..
pthread of main  exit...
p = 0x7f604c0008c0 *p = 20
pthread join over..

猜你喜欢

转载自www.cnblogs.com/it8343/p/9241882.html
今日推荐