2013-03-30 34 views
0

我試圖壓縮包含1和0的文件作爲賦值的一部分。我成功地做到了這一點,但是爲了感受線程,我試圖用pthread顯示一個簡單的進度顯示。問題是線程在壓縮完成後執行。下面是我的程序:pthread在預期之後執行

void* compressShow(void *) 
    { 
     pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); 
     pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); 

    cout<<"Compressing"; 

    while(1) 
    { 
     sleep(1); 
     cout<<"."; 
     sleep(1); 
     cout<<"."; 
     sleep(1); 
     cout<<"."; 
     sleep(1); 
     cout<<"."; 
     cout<<"\b\b\b\b"; 
    } 

} 

void compression(char *buffer, ofstream &outFile) 
{ 
    //Some Compression code. Function executes each time a new line is lifted off the file. 
} 

int main(int argc, char *argv[]) 
{ 

    if(argc < 3) 
    { 
     cout<<"You entered an insufficient number of command line arguments."<<endl; 
    } 

    else 
    { 
     ifstream inFile; 
     inFile.open(argv[1], ios::in); 
     ofstream outFile(argv[2]); 

     char buffer[100] = {NULL}; 

     pthread_t thread; 
     pthread_attr_t attribute; 

     pthread_attr_init(&attribute); 
     pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_DETACHED); 

     pthread_create(&thread, &attribute, compressShow, (void *)5); 

     while(inFile.good()) 
     { 
    `  inFile.getline(buffer, 100, '\n'); 
      compression(buffer, outFile); 
     } 

     pthread_cancel(thread); 
     //pthread_join(thread, NULL); 
    } 

    return 0; 

} 

自從我創建線程之前while循環,我希望它與正在做的壓縮循環同時運行。

+0

你爲什麼創建線程分離?如果通過以下方式創建脫機的線程,則無法使用pthread_join:http://pubs.opengroup.org/onlinepubs/7990989799/xsh/pthread_attr_setdetachstate.html – Etherealone

+0

另外,這將是在創建的線程中執行工作的更好方法並在主線程中(在worker線程上調用pthread_tryjoin_np)將這些點放在屏幕上(處理I/O)。 – Etherealone

+0

因爲我試圖獨立於main所做的工作來執行它。 –

回答

1

這與線程無關。看到

int main() 
{ 
    compressShow(0); 
} 

嘗試發送flush手不時同樣的效果。

+0

對不起,我不明白你的意思。 :/ –

+1

線程運行良好,但是由於您未發送換行符,因此輸出緩衝區已被緩衝。克服這一點,比如說「cout <<」。「 << flush;' – fizzer

+0

這似乎解決了它。謝謝! 但是,您是否也可以告訴我在這種情況下做什麼刷新?我以前從未遇到過這個問題。 –