pthread(一)

#include <iostream>

#ifdef __cplusplus
extern "C" {
#endif

#include<pthread.h>

#ifdef __cplusplus
}
#endif

using namespace std;

void* do_task(void* params);

int main()
{
    cout << "Hello World!" << endl;
    pthread_t pt_1,pt_2;
    int index_1=1,index_2=2;
    int err_1=pthread_create(&pt_1,NULL,do_task,&index_1);
    int err_2=pthread_create(&pt_2,NULL,do_task,&index_2);
    if(err_1!=0 || err_1!=0){
        cout<<"create thread failed"<<endl;
    }
    int count=0;
    while (count<5) {
        count++;
        cout<<"main thread do "<<count<<endl;
    }
    pthread_join(pt_1,NULL);
    pthread_join(pt_2,NULL);
    cout<<"all finish"<<endl;
    return 0;
}

void* do_task(void* params){
    int count=0;
    while (count<5) {
        count++;
        cout<<"sub "<<*( (int*) params)<<" thread do "<<count<<endl;
    }
    pthread_exit(NULL);
}


TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp

LIBS += -lpthread

1、pthread_create()

typedef unsigned long int pthread_t;

int pthread_create(pthread_t * thread, pthread_attr_t attr, void * (*start_routine)(void *), void * arg);

attr:这个参数用于设置线程属性,NULL则采用默认属性

start_routine:异步调用函数

arg:start_routine的传入参数

这个函数创建成功之后立即进入异步线程中并执行start_routine,同时返回0。若失败返回非0错误代码。

常见的错误代码有EAGAIN线程数达到上限,EINVAL线程属性非法。

2、pthread_join()

在当前线程中等待指定线程运行结束。

这是一个阻塞函数,此函数会等待指定线程运行结束才会返回并回收指定线程的资源。

extern int pthread_join (pthread_t __th, void **__thread_return);

__th:线程标识符,即pthread_create创建的pthread_t 

__thread_return:线程返回值,即pthread_create里面start_routine函数指针的返回值的引用

3、pthread_exit()

线程退出有两种方式,第一种是线程函数运行结束不需要返回结果。第二种是通过在线程结尾调用pthread_exit()将结果传出来。

extern void pthread_exit (void *__retval) __attribute__ ((__noreturn__));

__retval:线程所执行的函数(pthread_create传入的函数指针)的返回值,可以被pthread_join 捕获。










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值