C:如何安全,正确地传递几个参数到pthread的? [英] C: How to safely and properly pass several arguments to a pthread?
问题描述
考虑一个简单的code:
Consider this simple code:
void* threadFunction(void* arg) {
int argument=(int)arg;
printf("%d recieved\n", argument);
return NULL;
}
int main(int argv, char* argc[]) {
int error;
int i=0;
pthread_t thread;
int argument_to_thread=0;
if ((error=pthread_create(&thread, NULL, threadFunction, (void*)argument_to_thread))!=0) {
printf("Can't create thread: [%s]\n", strerror(error));
return 1;
}
pthread_join(thread, NULL);
return 0;
}
这工作,但两件事情在这里打扰我。结果
首先,我要多于一个参数发送到threadFunction()。结果
当然,我可以传递一个指向数组的指针,但如果我想通过不同类型的两个参数是什么? (比方说一个 INT
和的char *
)如何能不能做到?
This works, but two things bother me here.
First, I want to send more than one argument to threadFunction().
Of course, I can pass a pointer to an array, but what if I want to pass two arguments of different types? (say an int
and char*
) How can it be done?
在这里困扰我的第二件事,就是编制以上时,我得到了警告...
The second thing that bothers me here, is the warnings I get when compiling the above...
test2.c: In function ‘threadFunction’:
test2.c:8:15: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
int argument=(int)arg;
^
test2.c: In function ‘main’:
test2.c:24:59: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
if ((error=pthread_create(&thread, NULL, threadFunction, (void*)argument_to_thread))!=0) {
^
现在,我可以让这个去如这样做:
Now, I can make this go away by doing this:
if ((error=pthread_create(&thread, NULL, threadFunction, (void*)&argument_to_thread))!=0) {
printf("Can't create thread: [%s]\n", strerror(error));
return 1;
}
但是,让我们说,我不希望通过引用传递吧...有没有办法作为参数传递,比如......一个int,由值,而编译器警告我?
But let's say I don't want to pass it by reference... Is there way to pass, say... an int, by value as an argument without the compiler warning me?
推荐答案
有两种方法可以做到这一点:
There are two ways to do this:
-
使用
的malloc
来获得的参数结构存储,并有新的线程负责调用免费
一旦它的参数完成。 (注意:如果在pthread_create
失败,则需要免费
此存储中的失败路径。)
Use
malloc
to obtain storage for the arguments structure, and have the new thread be responsible for callingfree
once it's done with the arguments. (Note: ifpthread_create
fails, you need tofree
this storage in the failure path.)
使用信号量(或者其他同步,但信号是迄今为止最轻)。
Use a semaphore (or other synchronization, but a semaphore is by far the lightest).
下面是后者的一个例子:
Here's an example of the latter:
struct args {
int a;
char *b;
sem_t sem;
};
void *thread_func(void *p)
{
struct args *args = p;
int a = args->a;
char *b = args->b;
sem_post(args->sem);
...
}
/* in caller */
struct args args;
args.a = ...;
args.b = ...;
sem_init(&args.sem, 0, 0);
pthread_create(&tid, 0, thread_func, &args);
sem_wait(&args.sem);
...
这篇关于C:如何安全,正确地传递几个参数到pthread的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!