Linux下如何创建单个线程以及循环创建多个线程

创建线程的函数   

#include<pthread.h>
int pthread_create(pthread_t *restrict tidp,  const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
若成功返回0,否则返回错误编号

创建单个线程:

#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
using namespace std;

void* mythread(void *arg)
{
        cout<<"子线程"<<pthread_self()<<"       进程id:"<<getpid()<<endl;
}

int main()
{
        pthread_t pid;
        int err=pthread_create(&pid,NULL,&mythread,NULL);    //调用函数
        if(err != 0)
        {
                cout<<"create error"<<endl;
        }
        sleep(5);
        cout<<"该程序的进程id: "<<getpid()<<endl;
}

循环创建多线程:

创建多线程时不像多进程一样,子线程在下一次循环的时候不会重新创建子子线程,因此不用返回,而直接创建

#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
using namespace std;

void* mythread(void *arg)       //传入i值
{
        sleep((long)arg);
        cout<<(long)arg<<"子线程"<<pthread_self()<<"       进程id:"<<getpid()<<endl;
}

int main()
{
        pthread_t pid[5];

        int i;
        for(i=0;i<5;i++)       //循环创建多线程
        {
                int err=pthread_create(&pid[i],NULL,&mythread,(void *)(intptr_t)i);
                if(err != 0)
                {
                        cout<<"create error"<<endl;
                }
        }
        if(i==5)
        {
                sleep(i);        //等待子线程全部运行完
                cout<<"该程序的进程id: "<<getpid()<<endl;
        }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大学生毕设

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值