1
我正在用線程逼近C編程,我無法使該程序正常工作。基本上有一個向量包含k個元素,n個線程,每個線程必須計算其k/n個元素的最大值。線程執行問題
我的代碼是(請注意這不是整個代碼):
// Struct code used later
struct maxStruct
{
double *vettore;
int dimensione;
};
// Gathering data input from user
[ . . . ]
vector = (double *) malloc (dimensione * sizeof(double));
pid_thread = (int *) malloc (numero_thread * sizeof(int));
thread = (pthread_t *) malloc (numero_thread * sizeof(pthread_t));
// Generating the vector
[ . . . ]
for (i = 0; i < numero_thread; i++)
{
e = generaStruct(i, vettore, dimensione, numero_thread);
if (status = pthread_create(&thread[i], NULL, calcolaMassimo, (void *) e))
{
pthread_perror("pthread_join", status);
exit(1);
}
}
//Note that the function doesn't calculate the max, I've coded it in this way
//in order to see whether it was being called by each thread and apparently it is not.
void *calcolaMassimo(void * e)
{
printf("Sono chiamata!!\n");
struct maxStruct *sottoVettore = e;
printf("Dimensione: %d\n", ((*sottoVettore).dimensione));
}
顯然,這個功能沒有被每一個線程調用,我想不通爲什麼。你能幫我解決這個問題嗎?
你怎麼知道函數沒有被每個線程調用? Printf不是線程安全的;除非你同步訪問它,否則你不會得到你期望的結果。 – antlersoft
@antlersoft:在Linux的libc中,printf'實際上是線程安全的。 – 2011-07-11 18:02:49
創建線程後你在做什麼? –