在删除多个线程共享的 iostream 对象之前,主线程必须核实子线程已完成了对共享对象的使用。下例说明了如何安全销毁共享对象。
#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.
}
|