我試圖壓縮包含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循環,我希望它與正在做的壓縮循環同時運行。
你爲什麼創建線程分離?如果通過以下方式創建脫機的線程,則無法使用pthread_join:http://pubs.opengroup.org/onlinepubs/7990989799/xsh/pthread_attr_setdetachstate.html – Etherealone
另外,這將是在創建的線程中執行工作的更好方法並在主線程中(在worker線程上調用pthread_tryjoin_np)將這些點放在屏幕上(處理I/O)。 – Etherealone
因爲我試圖獨立於main所做的工作來執行它。 –