Information Technology Reference
In-Depth Information
intmain(intargc,char**argv)
{
TSQueue*queues[3];
sthread_tworkers[3];
intii,jj,ret;
boolsuccess;
//Starttheworkerthreads
for(ii=0;ii<3;ii++){
queues[ii]=newTSQueue();
sthread_create_p(&workers[ii],putSome,
queues[ii]);
void*putSome(void*tsqueuePtr)
{
intii;
TSQueue*queue=(TSQueue*)tsqueuePtr;
}
sthread_join(workers[0]);
for(ii=0;ii<100;ii++){
queue->tryInsert(ii);
//Removefromthequeues
for(ii=0;ii<3;ii++){
printf("Queue%d:\n",ii);
for(jj=0;jj<20;jj++){
success=queues[ii]->tryRemove(&ret);
if(success){
printf("Got%d\n",ret);
}
returnNULL;
}
}
else{
printf("Nothingthere\n");
}
}
}
}
Figure5.5: This code creates three TSQueue objects and adds and removes
some items from these queues. The full code is in TSQueueMain.cc. Note that
rather than creating threads using the sthreadcreate() function introduced
earlier, we use the sthreadcreatep() variation so that we can pass a pointer
to the newly created thread; in this case, we pass each newly created thread a
pointer to the queue it will use.
pointer or reference to it. Two common ways to provide a pointer to a shared
object to a thread are (1) providing a pointer to the shared object when the
thread is created and (2) storing references to shared objects in other shared
objects (e.g., containers). For example, a program might have a global, shared
(and synchronized!) hash table that threads can use to store and retrieve refer-
ences to other shared objects.
Example: Using the queue. Figure 5.5 shows a simple program that
creates three queues and then creates some threads that insert into these
queues. Finally, it removes 20 items out of each of the queues and prints the
values it removes. The initial, main thread allocates the shared queues on the
heap using new() , and each of the worker threads is provided a pointer to a
shared queue when it is created.
Warning: Nothing prevents you from writing a program that allocates a
shared object as an automatic variable in a procedure or method, but you should
Search WWH ::




Custom Search