[英]How to pass an argument to a pthread thread function in C?
Is it possible to pass an argument to the thread function in pthreads?是否可以将参数传递给 pthreads 中的线程 function? Say I create a thread:
假设我创建了一个线程:
int main() {
pthread_t t1;
pthread_create(&t1, NULL, callback, 10);
pthread_join(t1, NULL);
return 0;
}
And in callback
I would like to just print out the 10
.在
callback
中,我只想打印出10
。 My problem now is that as per the C pthread
API , the pthread_create()
function signature is:我现在的问题是,根据 C
pthread
API , pthread_create()
function 签名是:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
Can I pass a pointer to an integer to the thread function and how?我可以将指向 integer 的指针传递给线程 function 吗?
You could use a variable, like:您可以使用变量,例如:
int val = 10;
pthread_create(&t1, NULL, callback, &val);
pthread_join(t1, NULL);
...
And in the callback
:在
callback
中:
void* callback(void *arg)
{
int i = *(int *)arg;
....
return NULL;
}
Note that this works because the lifetime of val
is valid until the thread ( callback
) completes its execution as you wait with pthread_join()
.请注意,这是有效的,因为
val
的生命周期在您等待pthread_join()
时线程( callback
)完成其执行之前是有效的。 Otherwise, you may want to allocate memory dynamically (eg malloc
) and pass that object to the thread function.否则,您可能希望动态分配 memory (例如
malloc
)并将 object 传递给线程 ZC1C4245268E67A94FC1
For a single value of integer type not wider than intptr_t
, it possible and fairly common to cast it to a pointer in the pthread_create
call and cast it back in the thread function:对于不比
intptr_t
宽的 integer 类型的单个值,在pthread_create
调用中将其转换为指针并将其转换回线程 function 是可能且相当普遍的:
int main() {
pthread_t t1;
pthread_create(&t1, NULL, callback, (void *) 10);
pthread_join(t1, NULL);
return 0;
}
void *t1(void *arg) {
int arg_as_int = (int) arg;
// ...
}
Such casting is definitely allowed, and again, is pretty conventional.这种铸造绝对是允许的,而且是非常传统的。
I have recently started seeing objections to this approach here on SO, however, on the basis that the C standard allows the first of those casts to produce a trap representation, and that it does not require the round-trip of int
to void *
to int
to be value-preserving.我最近开始在 SO 上看到对这种方法的反对意见,但是,基于 C 标准允许这些转换中的第一个产生陷阱表示,并且它不需要
int
往返void *
到int
是保值的。 That argument characterizes the C standard correctly, but it disregards the facts that as a practical matter, the casting approach works on substantially every C implementation that supports pthreads in the first place, and that it is common enough that an implementation on which it did not work reliably would have difficulty being accepted.该论点正确地描述了 C 标准的特征,但它忽略了以下事实,即作为实际问题,强制转换方法基本上适用于支持 Z4069B248C57DD4625F9E019410AEB90 的所有 C 实现,而不是最常见的实现,可靠的工作很难被接受。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.