c++ 头文件pthread.h如何给一个带自定义参数的函数开启多线程
时间: 2024-03-22 22:37:01 浏览: 92
可以使用pthread_create函数创建一个新线程,同时将自定义参数传递给新线程中的函数。具体的步骤如下:
1. 定义一个自定义结构体,用于存储传递给新线程中的函数的参数。
```
typedef struct {
int arg1;
char* arg2;
} ThreadArgs;
```
2. 定义一个函数,该函数即为将被新线程执行的函数。
```
void* threadFunction(void* args) {
ThreadArgs* t_args = (ThreadArgs*) args;
int arg1 = t_args->arg1;
char* arg2 = t_args->arg2;
// 在这里执行线程的任务
pthread_exit(NULL);
}
```
3. 在主线程中创建新线程,并传递自定义参数。
```
ThreadArgs t_args;
t_args.arg1 = 123;
t_args.arg2 = "Hello World";
pthread_t thread;
int result = pthread_create(&thread, NULL, threadFunction, (void*) &t_args);
if (result != 0) {
printf("Error: Failed to create thread.\n");
exit(EXIT_FAILURE);
}
```
在上述代码中,pthread_create函数的第一个参数是指向新线程的标识符的指针,第二个参数是线程的属性,可以设置为NULL表示使用默认属性。第三个参数是指向新线程将要执行的函数的指针,第四个参数是传递给新线程函数的参数,需要强制转换为void*类型。在新线程中,需要使用pthread_exit函数来退出线程。
阅读全文
相关推荐
















