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

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

1.创建线程

#include <pthread.h>
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 <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

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 <pthread.h>
int pthread_cancel(pthread_t thread);

thread是取消的线程ID。
实例

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

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 <pthread.h>
int pthread_join(pthread_t thread,void **value_ptr);

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

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

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;
}

要很努力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值