2013-03-02 20 views
0

我很感激任何幫助,並且想提前感謝您。我正在爲我的一個課程開發一個項目。基本上使用多線程和引用類來執行合併排序。在主要我只是想創建一個初始線程,將開始遞歸mergesort。每次拆分數組時,都會生成一個新線程來處理該子例程。我不需要所有的工作,我只是不支持爲什麼我的線程構造函數和ThreadStart委託不工作。再次感謝!!使用引用類在C++中多線程 - ThreadStart構造函數問題?

#include <iostream> 
#include <vector> 
#include <string> 
#include <time.h> 
#include <cstdlib> 

using namespace System; 
using namespace System::Threading; 

public ref class MergeSort 
{ 
    private: int cnt; 

    public: MergeSort() 
    { 
     cnt = 0; 
    } 

    public: void mergeSort(char a[], int from, int to) 
    { 
     Thread^ current = Thread::CurrentThread; 

     if(from == to) 
      return; 
     int mid = (from + to)/2; 

     //Sort the first and the second half 
     //addThread(a, from, mid); 
     //addThread(a, mid+1, to); 

     //threads[0]->Join(); 
     //threads[1]->Join(); 

     merge(a, from, mid, to); 
    } 

    public: void merge(char a[], int from, int mid, int to) 
    {   
      Thread^ current = Thread::CurrentThread; 
      while (current ->ThreadState == ThreadState::Running) 
      { 
        int n = to-from + 1; // Size of range to be merged 
        std::vector<char> b(n); 

        int i1 = from; //Next element to consider in the first half 
        int i2 = mid + 1; //Next element to consider in the second half 
        int j = 0; //Next open position in b 

        //As long as neight i1 or i2 is past the end, move the smaller element into b 
        while(i1 <= mid && i2 <= to) 
        { 
         if(a[i1] < a[i2]) 
         { 
          b[j] = a[i1]; 
          i1++; 
         } 
         else 
         { 
          b[j] = a[i2]; 
          i2++; 
         } 
         j++; 
        } 

        //Copy any remaining entries of the first half 
        while(i1 <= mid) 
        { 
         b[j] = a[i1]; 
         i1++; 
         j++; 
        } 
        while(i2 <= to) 
        { 
         b[j] = a[i2]; 
         i2++; 
         j++; 
        } 

        //Copy back from temporary vector 
        for(j = 0; j < n; j++) 
         a[from+j] = b[j]; 
      }  
    } 
}; 


void main() 
{ 
    char A[10]; 

    for(int i = 0; i < 10; i++) 
    { 
     A[i] = ((char) ((rand() % (122-65)) + 65)); 
    } 

    array<Thread^>^ tr = gcnew array<Thread^>(10); 

    MergeSort^ ms1 = gcnew MergeSort(); 

    ThreadStart^ TS = gcnew ThreadStart(ms1, &MergeSort::mergeSort(A, 0, 10)); 
    tr[0] = gcnew Thread(TS); 
    tr[0] -> Start(); 

    system("pause"); 
} 
+1

爲什麼你使用'^'指針?你是否與pascal(或delphi)混合? – didierc 2013-03-02 01:59:57

+0

這是C++的一些微軟風格嗎? – 2013-03-02 02:09:51

+1

爲什麼不'std :: thread' – 111111 2013-03-02 02:11:41

回答

0

你面對這裏的問題是如何構建一個ThreadStart委託。您正在嘗試在構造函數ThreadStart中執行太多操作。您目前無法傳入參數,因爲它正在查找的是該線程的起始位置。

的代表應該是:然而

ThreadStart^ TS = gcnew ThreadStart(ms1, &MergeSort::mergeSort); 

既然你是在傳遞一些狀態,我建議做如何正在使用C++ \ CLI做了些研究。 This MSDN topic應該給你一個開始。

+0

是的,線程委託不能有參數,謝​​謝你的提示。不過,我正在使用不允許CLI成員的CLR。 – Elysium 2013-03-07 01:18:51