gpt4 book ai didi

c - pthread_join seg 故障核心转储

转载 作者:行者123 更新时间:2023-11-30 19:15:45 26 4
gpt4 key购买 nike

我在 pthread_join 行收到段错误。下面是我的线程创建和加入代码以及我正在调用的 my_func 线程函数。该程序应该创建可变数量的线程来执行类似 grep 的函数。

int                             
parallelSearchStatic(char **argv)
{
pthread_t worker_thread[NUM_THREADS];
ARGS_FOR_THREAD *args_for_thread;
queue_element_t *element;
int i;
int num_occurrences = 0;
int queue_count = 0;

queue_t *queue = createQueue(); /* Create and initialize the queue data structure. */

DIR *d;
struct dirent *dir;
d = opendir(argv[2]);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
element = (queue_element_t *)malloc(sizeof(queue_element_t));
if(element == NULL){
perror("malloc");
exit(EXIT_FAILURE);
}

strcpy(element->path_name, argv[2]);
strcat(element->path_name, "/");
strcat(element->path_name, dir->d_name);

insertElement(queue, element);
queue_count++;
}

closedir(d);
}

int increment = queue_count/NUM_THREADS;

for(i=0;i<NUM_THREADS;i++){

args_for_thread = (ARGS_FOR_THREAD *)malloc(sizeof(ARGS_FOR_THREAD));
args_for_thread->threadID=i;
args_for_thread->queue=createQueue();
args_for_thread->args=argv;

for(i = 0; i < increment; i++)
{
insertElement(args_for_thread->queue, removeElement(queue));
queue_count--;
}

if(i == (NUM_THREADS - 1) && queue_count != 0)
{
for(i = 0; i < queue_count; i++)
{
insertElement(args_for_thread->queue, removeElement(queue));
}
}

if((pthread_create(&worker_thread[i], NULL, my_func, (void *)args_for_thread))!=0){
printf("Cannot create thread \n");
exit(0);
}

}

for(i=0;i<NUM_THREADS;i++)
{
pthread_join(worker_thread[i], NULL);
}

for(i = 0; i < NUM_THREADS; i++)
num_occurrences += countArray[i];

return num_occurrences;
}

void *my_func(void *this_arg)
{
ARGS_FOR_THREAD *args_for_me = (ARGS_FOR_THREAD *)this_arg; // Typecast the argument passed to this function to the appropriate type

int threadID = args_for_me->threadID;
queue_t *queue = args_for_me->queue;
char** args = args_for_me->args;

int count = 0;

while(queue->head != NULL)
{
queue_element_t *element = removeElement(queue);

char *a[5];

a[0] = args[0];
a[1] = args[1];
a[2] = element->path_name;
a[3] = args[3];
a[4] = args[4];

count += serialSearch(a);
}

countArray[threadID] = count;

free((void *)args_for_me); // Free up the structure
pthread_exit(NULL);
}

最佳答案

您在外部循环内的嵌套循环中重用 i,该循环也使用 i 作为其计数器变量:

for(i = 0; i < increment; i++)

for(i = 0; i < queue_count; i++)

这意味着您的 pthread_create() (遵循这些内部循环)正在使用错误的 i 值来访问 worker_thread[i],因此 worker_thread[] 的某些值仍未初始化,然后导致 pthread_join() 崩溃。

对内部循环使用不同的变量(例如j)。

关于c - pthread_join seg 故障核心转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31910565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com