Oracle Solaris Studio 12.2:C++ 用户指南

10.4.7 对象析构

在删除多个线程共享的 iostream 对象之前,主线程必须核实子线程已完成了对共享对象的使用。下例说明了如何安全销毁共享对象。


示例 10–12 销毁共享对象


#include <fstream.h>
#include <thread.h>
fstream* fp;

void *process_rtn(void*)
{
    // body of sub-threads which uses fp...
}

void multi_process(const char* filename, int numthreads)
{
    fp = new fstream(filename, ios::in); // create fstream object
                                         // before creating threads.
    // create threads
    for (int i=0; i<numthreads; i++)
            thr_create(0, STACKSIZE, process_rtn, 0, 0, 0);

        ...
    // wait for threads to finish
    for (int i=0; i<numthreads; i++)
            thr_join(0, 0, 0);

    delete fp;                          // delete fstream object after
    fp = NULL;                         // all threads have completed.
}