吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1188|回复: 0
收起左侧

[C&C++ 转载] 线程的创建和删除

[复制链接]
github_520 发表于 2020-11-29 19:48
多线程1.线程的创建和删除pthread_create - create a new threadSYNOPSIS       #include <pthread.h>int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);
&#8203;
   Compile and link with -pthread.#include <iostream>
#include<pthread.h>
using namespace std;
#define NUM 10
void* say_hello(void* args)
{
    cout<<"Hello Runoob"<<endl;
    return 0;
}
int main() {
    std::cout << "Hello, World!" << std::endl;
    pthread_t tids[NUM];
    for(int i=0;i<NUM;i++)
    {   //pthread_create (thread, attr, start_routine, arg) 产生新的线程 成功则返回0
        int ret=pthread_create(&tids,NULL,say_hello,NULL);
        if(ret!=0)
        {
            cout<<"pthread_create error: error_code= "<<ret<<endl;
        }
    }
    pthread_exit(NULL);//pthread_exit (status)
    return 0;
}
&#8203;pthread_create 产生线程 pthread_exit 退出线程2. void (start_routine) (void *), void *arg); 传递参数形式#include<iostream>
#include<pthread.h>
#include<cstdlib>
#define NUM 5
using namespace std;
void *PrintHello(void *threadid)
{
    int tid=*((int *)threadid);
    cout<<"Hello Runoob ! ID: "<<tid<<endl;
    pthread_exit(NULL);
}
int main()
{
pthread_t thread[NUM];
int index[NUM];
int rc,i;
for(i=0;i<NUM;i++)
{
    cout<<"main(): 创建线程  "<<endl;
    index=i;//保存i的值
    rc=pthread_create(&thread,NULL,PrintHello,(void *)&(index));//最后一个参数是向函数传递的参数
    if(rc)
    {
        cout<<"Error:无法创建线程,"<<rc<<endl;
        exit(-1);
    }
}
pthread_exit(NULL);
}

免费评分

参与人数 1热心值 +2 收起 理由
PJwuaipojie + 2 热心回复!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-6 02:40

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表