Linux C/C++ 多线程

博客介绍了Linux环境下C++多线程编程的两个函数。pthread_create用于创建新子线程,需注意编译时链接线程库;pthread_join让当前线程等待指定线程结束并回收资源,根据等待线程状态可能阻塞或回收资源,还给出了程序实例。

一、pthread_create()函数

1、定义:

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

2、作用:

创建一个新的子线程,然后该子线程会执行start_routine()函数。若线程创建成功,则返回0。若线程创建失败,则返回出错编号。

3、参数:

thread:保存创建的新的子线程的线程号,同一个进程中的每一个线程的线程号是不相同的,但是不同的进程中的线程的线程号可以相同;

attr:设置创建的线程的属性 一般设置为NULL,表示使用默认属性;

start_rotine:线程的执行函数,也就是线程创建成功之后执行的函数。(注:该参数的类型是一个函数指针)

arg:传递给start_rotine()函数的参数。

4、注意:

使用线程函数的时候除了需要引入头文件#include <pthread.h>,还需要在编译的时候链接线程的线程库文件 g++ -o xxx xxx.cpp -lpthread

二、pthread_join()函数

1、定义:

int pthread_join(pthread_t thread, void **retval)

2、作用:

让当前线程等待指定的线程结束,并且当等待的线程结束之后就回收该线程的资源。若成功,则返回0;若失败,返回的是错误号。

3、参数:

thread:要等待的线程的线程id;

retval:接收等待的线程结束时的返回值。

4、注意:

根据等待的线程是否结束,可能有两种情况:
1 等待的线程尚未结束,则pthread_join()会陷入阻塞;
2 等待的线程已经结束,则pthread_join()会将线程的返回值(void *类型)存放到retval指针所指向的位置,并且回收该线程的资源。

三、程序实例:

#include <iostream>
#include <pthread.h>
#include <string>
#include <ctime>
#include <unistd.h>

using namespace std;

void* run(void *num)
{
        for(int i = 1; i < 100; i += 2)
        {
                cout << pthread_self() << ' ' <<  i << endl;
                sleep(1);
        }
        return nullptr;
}

int main()
{
        pthread_t pid;
        void* (*frun) (void*) = run;
        pthread_create(&pid, nullptr, frun, nullptr);
        cout << pthread_self() << endl;
        /*srand(time(nullptr));
        while(1)
        {
                cout << rand() % 10000 << endl;
                sleep(1);
        }*/
        pthread_join(pid, nullptr);
        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值