21xrx.com
2024-09-20 05:47:53 Friday
登录
文章检索 我的文章 写文章
Linux C++如何带参数创建线程?
2023-06-29 10:29:12 深夜i     --     --
Linux C++ 线程 参数 创建

Linux下,C++语言中的线程是由pthread库提供的,在使用pthread库时,可以通过pthread_create函数来创建一个新线程,并指定它的起始函数和传递的参数。本文将介绍如何在Linux下使用C++带参数创建线程。

1. 准备工作

在使用pthread库前,需要包含其头文件:


#include <pthread.h>

并链接libpthread库:


g++ -pthread your_code.cpp -o your_program

2. 创建线程

pthread_create函数的原型如下:


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

其中,thread是新线程的ID(pthread_t类型),attr是线程属性,start_routine是起始函数,arg是传递给起始函数的参数。

要创建线程,需要将起始函数封装成一个函数指针,并将参数传递进去。例如:


void *thread_func(void *param) {

  int *data = (int*) param;

  //do something with data

  return NULL;

}

int main() {

  int data = 42;

  pthread_t tid;

  pthread_create(&tid, NULL, thread_func, &data);

  //do something in main thread

  pthread_join(tid, NULL);

  return 0;

}

可以看到,创建线程的过程比较简单,只需将起始函数的地址作为参数传递给pthread_create函数,同时将参数的地址作为第四个参数传递进去即可。在创建线程之后,主线程可以进行其他操作,最后通过pthread_join函数等待新线程结束。

3. 传递复杂参数

上面的例子中,我们将整型变量作为参数传递给了新线程的起始函数。但如果需要传递更加复杂的参数,该怎么办?

一种常见的方式是将参数打包成一个结构体,然后将结构体的地址作为参数传递给起始函数。例如:


#include <iostream>

#include <pthread.h>

using namespace std;

struct thread_arg

  int a;

  float b;

  char c;

;

void *thread_func(void *param) {

  thread_arg arg = *((thread_arg*)param);

  cout << arg.a << " " << arg.b << " " << arg.c << endl;

  return NULL;

}

int main() {

  thread_arg arg = 3.14;

  pthread_t tid;

  pthread_create(&tid, NULL, &thread_func, &arg);

  pthread_join(tid, NULL);

  return 0;

}

在上面的例子中,我们定义了一个thread_arg结构体,该结构体包含了一个整型变量、一个浮点型变量和一个字符变量。然后我们将结构体的地址作为参数传递给起始函数,起始函数中使用指针取出结构体中的数据,并进行处理。

4. 小结

本文介绍了如何在Linux下使用C++带参数创建线程。在使用pthread_create函数时,可以将起始函数和参数打包成一个结构体,然后将结构体的地址作为参数传递给pthread_create函数。这样可以方便地传递复杂的参数,并在新线程中进行处理。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复