2010-03-10 33 views
0

我正在嘗試使用多線程實現c中的奇偶轉置排序算法。該程序將收到一個文件,其中包含需要正確排序的一行整數。我已經創建了該程序將使用的數組,並且正在正確讀取數據。雖然,我不太清楚如何正確創建線程。我知道我需要的線程數量總是N/2。然而N不會總是20,所以我現在處理的是有限的數量。這是一個限制,雖然B/C N不會總是20.它可能會更高。我的程序現在只能處理二十個。即使我已經有一個名爲swap的函數,我也遇到了排序部分的問題。起點功能就是這一切發生的地方。我不確定該問題的起始位置。如何在奇偶排序程序中正確創建線程和排序?

這是我到目前爲止的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <pthread.h> 

int list[20]; 
int n = 20; 
int param[10]; 

pthread_t threads[10]; 

void readLINE(char *filename); 
void do_swap(int R1, int R2); 
void display(); 
void *startPoint(void *arg); 


void readLINE(char *filename) 
{ 
    FILE* file; 
    int i,j; 
    file = fopen(filename,"r"); 
    if(file==NULL) 
    { 
     printf("Error: can't open file.\n"); 
} 
else 
{ 
    printf("File opened successfully.\n"); 

    i = 0; 
    while(!feof(file)) 
    { 
     fscanf(file,"%d", &list[i]); 
     i++; 
    } 

    printf("The numbers are: \n"); 
    for(j=0; j< i-1; j++) 
    { 
     printf("%d\n", list[j]); 
    } 

    fclose(file); 
} 

n = i-1; 

} 

//swap positions of arguments in list array 
void swap(int R1, int R2) 
{ 
if (list[R1] > list[R1+1]) 
{ 
    int temp = list[R1]; 
    list[R1] = list[R2]; 
    list[R2] = temp; 
} 
} 

void display() 

{ 
    int count; 
    for (count = 0; count < n; count++) 

    { 
     //cout << list[count] << " " ; 
     printf("%d ",list[count]); 
    } 
    //cout << endl; 
    printf("\n"); 
} 

void *startPoint(void *arg) 
{ 

int R1 = *(int*)arg; 

int count; 
for (count = 0; count < n/2; count++) 
{ 

} 
return 0; 
} 

int main(int argc, char** argv) 
{ 
pthread_attr_t tattr; 

pthread_attr_init (&tattr); 
pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM); 


readLINE(argv[1]); 
printf("list[] presorted:"); 
display(); 

//create n/2 threads to do the sorting algorithm 
//the parameter to each thread is an int: 
//first thread param is 0 
//second thread param is 2 
//third thread param is 4 etc.... 
int count; 
for (count = 0; count < n/2; count++) 
{ 
    param[count] = count*2; 
    pthread_create(&threads[ count], NULL, startPoint, (void*) &param[count]); 
} 

//wait for all the reads to finish before exiting the program 
//otherwise the process would exit and abort all the threads 

for (count = 0; count < n/2; count++) 
{ 
    pthread_join(threads[count], NULL); 
} 

//display the sorted state of the list 
printf("list[] after sorting: "); 
display(); 

exit(0); 
} 

回答

2

它已經因爲我寫標準的C代碼大約10年來,所以請原諒任何小錯誤。我確實認爲我可以在概念上幫助你。

您正在靜態分配緩衝區。相反,請確定所涉及的大小並動態分配所需的內存。這是一個good reference。基本確定n當你在文件中讀取,並使用malloc分配列表參數基於該值而不是分配固定的數組。

您對排序部分有什麼具體問題?你會得到一個編譯器錯誤,運行時錯誤,排序結果不正確,......?

UPDATE:

這裏的a discussion of serial and parallel sorting包括平行奇偶過渡的C.

+0

排序我沒有得到任何錯誤與分選部分,該功能還沒有被寫入的實現。我很困惑如何使用線程與實際的排序部分進行交互。 – saltinyellow 2010-03-11 00:21:25

+0

更新了包含實現的參考。建議你研究而不是複製實施,以最大限度地學習。 – 2010-03-11 00:50:46

+0

謝謝你的實現,一旦我計算出如何與線程進行交互。我可能會有更多的見解。 – saltinyellow 2010-03-11 01:11:16