【发布时间】:2014-06-15 10:47:43
【问题描述】:
我正在用 C 创建一个小程序,它计算用户输入的数字的能力,直到用户输入一个负数。它使用线程来做到这一点。
我在运行时遇到分段错误,所以我做错了什么,但我不知道具体是什么。
这是我的代码:
/*
* File: main.c
* Author: thomasvanhelden
*
* Created on June 15, 2014, 3:17 AM
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/**
* Calculates faculty of given number
* Can run as a thread
* @param param The given number
* @return Doesn't return anything
*/
void *fac(void *param) {
int* number = (int*) param;
int faculty = 1;
int i; // counter
printf("De faculteit van %i is: ", number);
for (i = 2; i <= number; i++) {
faculty *= i;
}
printf("%i\n", faculty);
}
/*
*
*/
int main(int argc, char** argv) {
pthread_t **threads;
int getal, numThreads = 0, counter, stop = 0;
// ask for numbers until user enters negative number
while (stop == 0) {
scanf("%i", getal);
if (getal >= 0) {
numThreads++;
threads = realloc(threads, sizeof(pthread_t*) * (numThreads+1));
threads[numThreads - 1] = malloc(sizeof(pthread_t));
// Create the thread
if (pthread_create(&threads[numThreads - 1], NULL, fac, &getal)) {
// something went wrong
printf("Error creating thread %i!\n", numThreads);
return 1;
}
} else {
// User entered negative number and wants to stop
stop = 1;
}
}
// join all the threads
for (counter = 0; counter < numThreads; counter++) {
if (pthread_join(threads[counter], NULL)) {
printf("Something went wrong joining thread %i\n", counter + 1);
}
}
return (EXIT_SUCCESS);
}
【问题讨论】:
标签: c multithreading dynamic pthreads