C++: 多线程pthread编程

源文件

#include <iostream>
// 必须的头文件是
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define NUM_THREADS 5

// 线程的运行函数
void* say_hello(void* args)
{
    int* x = (int *)&args;
    cout << "\nHello w3cschool!" << "ID: " << *x << endl;
}

int main()
{
    // 定义线程的 id 变量,多个变量使用数组
    pthread_t tids[NUM_THREADS];
    for(int i = 0; i < NUM_THREADS; ++i)
    {
        //参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
        int ret = pthread_create(&tids[i], NULL, say_hello, (void *)i);
        if (ret != 0)
        {
           cout << "pthread_create error: error_code=" << ret << endl;
        }
    }
    //等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
    pthread_exit(NULL);
}

编译

g++ pthread_main.cpp -lpthread -o pthread_main
fengxuewei@fengxuewei-Legion-Y7000-2019-PG0:~/UAV/C++_Folder/learn$ ./pthread_main 

Hello w3cschool!ID: 0

Hello w3cschool!ID: 3

Hello w3cschool!ID: 2

Hello w3cschool!ID: 1

Hello w3cschool!ID: 4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值