c++ - pthread 在预期之后执行

标签 c++ linux multithreading ubuntu posix

我正在尝试压缩一个由 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/

相关文章:

c++ - 如何使 MATLAB 函数在 html 中运行?

c++ - 为什么#define 不好?

linux - 使用 awk 或 sed 获取两个单词之间的值

c# - 像在 c# 中一样将整个类作为参数传递给线程 c++

c++ - 具有相互独立线程的多线程开销

C++ - 绕过 WinSock Hook

c++ - 我可以在两个 istream_iterators 之间进行赋值操作吗?

python - 如果我的一个程序在 python 2.4 中运行,但导入了一些需要 python 2.5 的东西怎么办?

linux - 我刚刚在运行 Ubuntu 的新服务器上运行我的新 node.js/express 应用程序,我如何查看我的 Web 应用程序?

Java:使用 ArrayList 创建堆栈