pthread在预期之后执行

时间:2013-03-30 19:09:17

标签: 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循环之前创建了线程,所以我希望它与正在进行压缩的循环同时运行。

1 个答案:

答案 0 :(得分:1)

这与线程无关。使用

看到相同的效果
int main()
{
    compressShow(0);
}

尝试不时发送flush操纵器。