使用Struct将String数组和索引传递给C中的线程

时间:2018-09-17 02:07:39

标签: c multithreading struct pthreads

我试图传递一个字符串数组和索引,从该位置开始在数组中结束搜索,但是从最近两天开始我无法解决它。我要向pthread_create发送一个结构数据thread_data,在这里我可以发送int和long数据,但不能发送字符串数组,有人可以帮助我,如何传递这些数据。

struct data{
        int  tid;
        unsigned long start;
        unsigned long end;
        char * word;
        char * str;
        };

struct data thread_data[NUM_THREADS];
void *searchString(void *passeddata)
{
   struct data *t_data;
   int tid1;
   char * str[3];
   t_data=(struct data *) passeddata;
   tid1=t_data->tid;
   str=t_data->str;
  .....
   pthread_exit(NULL);
}       
int main(int argc, char *argv[])
{
...
char  work[]={"First Line","Second line","Third line"};
...

   while(fgets(arr[index],120, fp)!=NULL){
        index=index+1;
        thread_data[index].tid=index;
        thread_data[index].str=work;
        ...
        rc=pthread_create(&threads[index],NULL,searchString,(void *)&thread_data[index]);
...     
        }

   pthread_exit(NULL);
}

1 个答案:

答案 0 :(得分:0)

要容纳多个字符串,您需要2D数组。

const char  *work[]={"First Line","Second line","Third line", "Fourth Line"};

您需要使用指向struct data中的指针的指针来保存上述数组。

struct data{
        .....
        const char **str;
        size_t lenOfStr;
        };

然后将数组的长度从main函数显式传递给线程函数。

您的示例代码如下所示。

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
struct data{
        int  tid;
        unsigned long start;
        unsigned long end;
        char * word;
        const char **str;
        size_t lenOfStr;
        };

struct data thread_data[3];

void *searchString(void *passeddata)
{
   struct data *t_data;
   int tid1;
   const char **str = NULL;
   t_data=(struct data *) passeddata;

   tid1=t_data->tid;
   str=t_data->str;

  int i = 0;
   for (i = 0;i<t_data->lenOfStr;i++)
   printf("%s\n", str[i]);

   pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
        const char  *work[]={"First Line","Second line","Third line", "Fourth Line"};
        int index = 0;
        pthread_t threadid=0;

        thread_data[index].tid=index;
        thread_data[index].str=work;
        thread_data[index].lenOfStr = sizeof(work)/sizeof(*work); // Calculate the size of work here

        int rc=pthread_create(&threadid,NULL,searchString,&thread_data[index]);

        pthread_exit(NULL);
}