我正在尝试压缩一个由 1 和 0 组成的文件作为分配的一部分。我已经成功地做到了这一点,但是为了感受线程,我尝试使用 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 循环之前创建线程,所以我希望它与执行压缩的循环同时运行。
最佳答案
这与线程无关。查看与
相同的效果int main()
{
compressShow(0);
}
不时尝试发送flush
操纵符。
关于c++ - pthread 在预期之后执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15722373/