我正在尝试编写一个使用线程的并行模拟器。但我找不到导致段错误的原因以及为什么线程有时会卡在屏障上。
#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 如下
我实现障碍的方式有什么问题?段故障的原因是什么? 编辑: 使用较短版本的代码进行了更新。这段代码只是想创建 num_thread 个线程,每个线程都会将一个元素从数组复制到另一个元素。
最佳答案
void initializeThreads( struct ThreadArguments* data, char* letters)
{
int i;
pthread_barrier_t barrier; //create a barrier
您在initializeThreads
中在堆栈上创建了barrier
,因此当该函数返回时,它就不再存在。因此,您创建的所有线程都通过过时指针访问不再存在的对象。
关于c - Pthread 奇怪的行为和段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34391060/