pthread_create 有两个变量的传递函数
pthread_create pass function with two variable
谁能帮我知道是否可以将两个不同的变量发送到一个函数,该函数过去曾发送 pthread_create
?
void *handler(void *parameter){
//some code
return 0;
}
是否可以有这样的功能
void *handler(void *parameter, void *parameter2){
//some code
return 0;
}
如果可能,我如何将它与 pthread_create
一起使用?
提前致谢。
没有。 pthread_create
的 start_routine
应该是 void *(*) (void *)
.
形式的函数
这是pthread_create
的原型。
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
The thread is created executing start_routine
with arg
as its sole argument
如果您想向 handler
函数发送多个参数,那么您可以通过使 arg
指向包含这些参数的结构的指针来实现。
例如你可以这样做:
struct Params{
int i;
char c;
};
struct Params* pParams;
现在,您可以使用 (void*)pParams
。
代替 void* arg
作为由 pthread_create
创建的线程的起点的函数必须 接受单个 void *
作为参数并且 return一个void *
.
您需要用您的变量创建一个结构并传递一个指向它的指针。
struct thread_data {
int x;
int y;
};
void *handler(void *parameter){
struct thread_data *data = parameter;
...
return NULL;
}
int main()
{
pthread_t tid;
struct thread_data data = { 1, 2 };
pthread_create(&tid, NULL, handler, &data);
...
}
谁能帮我知道是否可以将两个不同的变量发送到一个函数,该函数过去曾发送 pthread_create
?
void *handler(void *parameter){
//some code
return 0;
}
是否可以有这样的功能
void *handler(void *parameter, void *parameter2){
//some code
return 0;
}
如果可能,我如何将它与 pthread_create
一起使用?
提前致谢。
没有。 pthread_create
的 start_routine
应该是 void *(*) (void *)
.
这是pthread_create
的原型。
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
The thread is created executing
start_routine
witharg
as its sole argument
如果您想向 handler
函数发送多个参数,那么您可以通过使 arg
指向包含这些参数的结构的指针来实现。
例如你可以这样做:
struct Params{
int i;
char c;
};
struct Params* pParams;
现在,您可以使用 (void*)pParams
。
void* arg
作为由 pthread_create
创建的线程的起点的函数必须 接受单个 void *
作为参数并且 return一个void *
.
您需要用您的变量创建一个结构并传递一个指向它的指针。
struct thread_data {
int x;
int y;
};
void *handler(void *parameter){
struct thread_data *data = parameter;
...
return NULL;
}
int main()
{
pthread_t tid;
struct thread_data data = { 1, 2 };
pthread_create(&tid, NULL, handler, &data);
...
}