我正在尝试编写一个使用线程的并行模拟器。但我找不到导致分段错误的原因以及为什么线程有时似乎卡在障碍上。
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
int num_threads = 5;
//Thread arguemnt struct
struct ThreadArguments {
unsigned int id;
pthread_barrier_t* barrier;
char* array;
char* copy_array;
};
void simulate(struct ThreadArguments* args);
void initializeThreads( struct ThreadArguments* data, char* letters);
// Main method
int main(int argc, char *argv[]) {
int i;
char* letters = malloc((num_threads + 1) *sizeof(char)); //plus 1 for /0
struct ThreadArguments *data = malloc(num_threads * sizeof(struct ThreadArguments));
initializeThreads(data, letters);
pthread_t *thread = malloc(num_threads*sizeof(pthread_t));
// Launching Threads
for (i=0; i<num_threads; i++) {
printf("Create threads %d \n", i);
fflush(stdout);
pthread_create(&thread[i], NULL,(void *) &simulate,(void *) &data[i]);
}
// Waiting for Threads to Finish
for (i=0; i<num_threads; i++) {
pthread_join(thread[i], NULL);
}
return 0;
}
void initializeThreads( struct ThreadArguments* data, char* letters)
{
int i;
pthread_barrier_t barrier; //create a barrier
pthread_barrier_init (&barrier, NULL, num_threads);
char *copy_letters = malloc((num_threads + 1) * sizeof(char));
if(copy_letters == NULL) //Checking malloc
{
perror("Error mallocing");
free(copy_letters);
return;
}
for (i = 0; i < num_threads; i++)
{
data[i].barrier = &barrier;
data[i].array = letters;
data[i].copy_array = copy_letters;
data[i].id = i;
}
}
void simulate(struct ThreadArguments* args)
{
struct ThreadArguments* my_args= (struct ThreadArguments*)args;
printf("thread %d started", my_args->id);
fflush(stdout);
if(my_args->id == 0) //print the initial state of the board
{
printf("0th thread prints out results");
}
///Main loop. Each iteration is one round of simulation
my_args->copy_array[my_args->id] = my_args->array[my_args->id];
//DO SOME WORK HERE
//barrier
pthread_barrier_wait (my_args->barrier);
}
我尝试注释掉部分并使用 valgrind(和 helgrind 工具)对其进行跟踪,但仍然无法理解导致错误的原因。可以使用 ./simulator test.txt 0 0 1 测试代码,其中 test.txt 如下
我实施障碍的方式有什么问题?是什么导致了 SEGFAULT?编辑:使用较短版本的代码进行了更新。这段代码只想创建 num_thread 个线程,每个线程将一个元素从数组复制到另一个。