我的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/