linux系统下多线程开发(创建线程、取消线程、等待线程)

linux系统下多线程开发(创建线程、取消线程、等待线程)

1.创建线程

#include 
int pthread_create(pthread_t *restrict thread,const pthread_attr_t *restrict attr,void *(*start_routine)(void*),void *restrict arg);

restrict修饰的指针所指向的数据是唯一的;如果创建线程成功,会返回0,thread是线程的ID;attr是设置线程的属性,一般为NULL,start_routine是一个函数指针,指向线程要执行的代码;arg是参数传入。

实例

#include 
#include 
#include 
#include 

void *thread_func(void *arg)    //线程函数
{
    int *val=arg;
    printf("this is Thread!\n");
    if(NULL!=arg)
    {
        printf("argument set:%d\n",*val);
    }
}

int main()
{
    pthread_t tid;            //线程ID
    int t_arg=100;            //传入参数
    if(pthread_create(&tid,NULL,thread_func,&t_arg))    //创建线程
    {
        perror("Fail to create thread");
    }
    sleep(1);
    printf("main thread!\n");
    return 0;
}

2.取消线程

#include 
int pthread_cancel(pthread_t thread);

thread是取消的线程ID。
实例

#include 
#include 
#include 
#include 

void *thread_func(void *arg)    //线程函数
{
    int *val=arg;
    printf("this is Thread!\n");
    if(NULL!=arg)
    {
        while(1)
        {
            printf("argument set:%d\n",*val);
        }
    }
}

int main()
{
    pthread_t tid;            //线程ID
    int t_arg=100;            //传入参数
    if(pthread_create(&tid,NULL,thread_func,&t_arg))    //创建线程
    {
        perror("Fail to create thread");
    }
    sleep(1);
    printf("main thread!\n");
    pthread_cancel(tid);    //取消线程
    return 0;
}

3.等待线程

#include 
int pthread_join(pthread_t thread,void **value_ptr);

value_ptr指向退出线程的返回值,如果成功返回0,失败返回出错代码。
实例

#include 
#include 
#include 
#include 

void* mid_thread(void *arg)
{
    int times =0;
    printf("mid thread created!\n");
    while(2)
    {
        printf("waitting term thread %d times!\n",times);
        sleep(1);
        times++;
    
    }
}

void* term_thread(void *arg)
{
    pthread_t *tid;
    printf("term thread created!\n");
    sleep(2);
    if(NULL!=arg)
    {
        tid=arg;
        pthread_cancel(*tid);
    }
}

int main()
{
    pthread_t mid_tid,term_tid;
    if(pthread_create(&mid_tid,NULL,mid_thread,NULL))
    {
        perror("create mid thread error!");
        return 0;
    }
    
    if(pthread_create(&term_tid,NULL,term_thread,&mid_tid))
    {
        perror("create term thread error!");
        return 0;
    }
    
    if(pthread_join(mid_tid,NULL))
    {
        perror("wait mid thread error!");
        return 0;
    }
    
    if(pthread_join(term_tid,NULL))
    {
        perror("wait term thread error!");
        return 0;
    }
    
    return 0;
}

要很努力!

你可能感兴趣的:(Linux)