Michael Maged

Andrei Alexandrescu andrei at metalanguage.com
Sun Oct 3 18:52:02 BST 2004


>>The 
>>delicate issue, I believe, will be to provide a memory model that will 
>>allow system-implemented primitives to mesh in seamlessly, as well as 
>>allowing users to implement their own if they need to.
> 
> 
> Yes. The issue of how to qualify/specify opaque functions becomes
> critical here. It would be nice if it were the case that say a lock()
> function could be marked in some way so as to be known to act an
> acquire wrt the memory model, and so on.

Maybe we don't need that if we do have, as Kevlin suggested, some 
pseudo-functions 'embedded' in the language, defined to interact with 
the memory in specific ways (think membar()). Then, all a library has to 
guarantee is that its own lock() function behaves as if it performs a 
membar() call at a point.

Having "special functions" or "special objects" is a backdoor way of 
changing the semantics of a language without adding syntax. This is not 
new; C++ already has typeid() and std::type_info, std::bad_exception, 
and maybe I'm forgetting a couple more. Java took this to the next step 
in that Object Runnable, or String are special, and so on.

So I think we're in good shape there. We just need to define enough 
pseudo-functions and pseudo-objects to guarantee people can implement 
the needed behaviors. Then, everything a library must do is define its 
effects in terms of those primitives.

I recall pthreads also do that, like pthread_lock() is guaranteed to 
issue a membar. Right?

> Good question. The dead minimum for (1) seems to be to define a Thread
> class, with ways to create, start, block, unblock, block-with-timeout,
> detect termination, and query status. You could then in principle
> build everything in (2), not that most people would want to --
> existing stuff must be able to comply.  Can this be done in a way that
> everyone is guaranteed to love, or at least tolerate?

I believe so. The way that I think would be most natural to the C++ 
community would be to have a start_thread template function that takes a 
  generic functor and returns a Thread object. The Thread object ought 
to be parameterized by the type returned by the functor. This way users 
can call query_result(). Here's a sketch:

template <class Result>
class thread {
   ...
public:
   void block();
   void block(unsigned int timeout);
   void unblock();
   Result query_result();
   Result force_result();
   ...
};

template <class Result, class Fun>
thread<Result> start_thread(Fun fun) {
   ...
}

A note - there are facilities in C++'s current standard library that 
allow you to pack a pointer to object and a pointer to member function 
in one functor. So starting a thread via a functor works with simple 
functions as well as with member functions.


Andrei






More information about the cpp-threads mailing list