学习笔记之编写多线程

带参数的多线程

int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void**start_rtn)(void*),void *restrict arg)
  • 成功返回0;
  • 参数
    • 线程id
    • 线程属性
    • 运行函数地址
    • 运行函数的参数
int pthread_join __P (pthread_t __th, void **__thread_return);
  • 参数
    • 线程id
    • 用户定义的指针,可以用来存储被等待线程的返回值
  • 线程阻塞函数,调用它的函数将一直等待到被等待的线程结束为止,函数返回时,资源回收。
void pthread_exit(void  *retval)
  • 线程退出,可以指定返回值,以便其他线程通过pthread_join()获取该线程的返回值,
  • pthread_exit(NULL)==return

exit()

  • 线程调用,整个进程挂,慎用
#include "head/main.h" //这是我自己写的头文件  其实就是把各种include写入一个文件

#define NUM_THREADS 5

struct thread_data
{
    int thread_id;
    char *message;
};

void *print_hellow(void *threadarg)
{
    struct thread_data *my_data;
    my_data=(struct thread_data *)threadarg;
    cout<<"thread_id:"<<my_data->thread_id<<" message:"<<my_data->message<<endl;
    pthread_exit(NULL);
}
int main()
{
    pthread_t threads[NUM_THREADS];
    struct thread_data td[NUM_THREADS];
    int rc;
    int i;
    for(i=0;i<NUM_THREADS;i++)
    {
        cout<<"main():create thread,"<<i<<endl;
        td[i].thread_id=i;
        td[i].message=(char *)"this is message";
        rc=pthread_create(&threads[i],NULL,print_hellow,(void*)&td[i]);
        if(rc)
        {
            cout<<"Error: unable to create thread,"<<rc<<endl;
            exit(-1);
        }
        pthread_join(threads[i],NULL);
    }
}


运行截图
在这里插入图片描述

原创文章 23 获赞 26 访问量 437

猜你喜欢

转载自blog.csdn.net/weixin_41672404/article/details/105767282
今日推荐