Download C++ Library Reference - Oracle Documentation
Transcript
CODE EXAMPLE 4-13
Using iostream Objects in an MT-Safe Way (Continued)
// read a line at a time
instr.getline(ibuf, thread_bufsize - 1, ’\n’);
if(instr.eof())
break;
// lock cout stream so the i/o operation is atomic
lockout.lock();
// tag line and send to cout
cout << (unsigned char)tt->thread_tag << ibuf << "\n";
lockout.unlock();
}
return 0;
}
int main(int argc, char** argv) {
// argv: 1+ list of filenames per thread
if(argc < 2) {
cout << “usage: " << argv[0] << " <files..>\n";
exit(1);
}
int num_threads = argc - 1;
int total_tags = 0;
// array of thread_ids
thread_t created_threads[thread_bufsize];
// array of arguments to thread entry routine
thread_args thr_args[thread_bufsize];
int i;
for( i = 0; i < num_threads; i++) {
thr_args[i].filename = argv[1 + i];
// assign a tag to a thread - a value less than 256
thr_args[i].thread_tag = total_tags++;
// create threads
thr_create(0, 0, ThreadDuties, &thr_args[i],
THR_SUSPENDED, &created_threads[i]);
}
for(i = 0; i < num_threads; i++) {
thr_continue(created_threads[i]);
}
for(i = 0; i < num_threads; i++) {
thr_join(created_threads[i], 0, 0);
}
return 0;
}
4-18
C++ Library Reference • May 2000