ç传递几个参数线程 [英] c passing several arguments to threads
本文介绍了ç传递几个参数线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我创建一个线程,我想通过几个参数。
所以我定义在头文件如下:
when i create a thread, i want to pass several arguments. So i define in a header file the following:
struct data{
char *palabra;
char *directorio;
FILE *fd;
DIR *diro;
struct dirent *strdir;
};
在.c文件我做以下
if (pthread_create ( &thread_id[i], NULL, &hilos_hijos, ??? ) != 0){
perror("Error al crear el hilo. \n");
exit(EXIT_FAILURE);
}
我如何通过这一切的参数传递给线程。我虽然一下:
How do i pass all this arguments to the threads. I though about:
1)首先使用malloc分配内存为这个结构,然后给每个参数的值:
1) first use malloc to allocate memory for this structure and then give each parameter a value:
struct data *info
info = malloc(sizeof(struct data));
info->palabra = ...;
2)定义
struct data info
info.palabra = ... ;
info.directorio = ...;
然后,我怎么在线程访问这些参数
无效thread_function(void *的参数){
???
}
and then, how do i access these parameters in the thread void thread_function ( void *arguments){ ??? }
在此先感谢
推荐答案
下面是一个工作(和相对较小的例子):
Here is a working (and relatively small example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
/*
* To compile:
* cc thread.c -o thread-test -lpthread
*/
struct info {
char first_name[64];
char last_name[64];
};
void *thread_worker(void *data)
{
int i;
struct info *info = data;
for (i = 0; i < 100; i++) {
printf("Hello, %s %s!\n", info->first_name, info->last_name);
}
}
int main(int argc, char **argv)
{
pthread_t thread_id;
struct info *info = malloc(sizeof(struct info));
strcpy(info->first_name, "Sean");
strcpy(info->last_name, "Bright");
if (pthread_create(&thread_id, NULL, thread_worker, info)) {
fprintf(stderr, "No threads for you.\n");
return 1;
}
pthread_join(thread_id, NULL);
return 0;
}
这篇关于ç传递几个参数线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文