Difference between revisions of "Uno/Article/Multi-Thread Programming"

From Apache OpenOffice Wiki
< Uno
Jump to: navigation, search
m (C++)
m (Moved "Threads" section to the end.)
Line 48: Line 48:
 
* not doing internal protection.
 
* not doing internal protection.
 
Such categorizations help to decide, what one can do with a particular implemention. Also the codes threading type is a compile time information and may therefor be used during compilation, so that the compiler may give errors when mixing [[Uno/Term/Thread Safe|thread safe]] and [[Uno/Term/Thread Unsafe|thread unsafe]] code in a multi thread scenario.
 
Such categorizations help to decide, what one can do with a particular implemention. Also the codes threading type is a compile time information and may therefor be used during compilation, so that the compiler may give errors when mixing [[Uno/Term/Thread Safe|thread safe]] and [[Uno/Term/Thread Unsafe|thread unsafe]] code in a multi thread scenario.
 
===Using Threads===
 
You may create threads in your implementation. Depending on the selected threading architecture, these threads may are allowed to be visible from the outside or not. If your implementation is to be instantiated in a
 
* [[Uno/Spec/Thread Unsafety Bridge|thread unsafe environment]], than it must be [[Uno/Term/Thread Transparent|thread transparent]], if it is to be used in a
 
* [[Uno/Spec/Thread Affinity Bridge|thread affine environment]], than is must be [[Uno/Term/Thread Transparent|thread transparent]] as well, if it is to be used in a
 
* [[Uno/Term/Thread Safe|thread safe]] environment, it may create visible threads and be [[Uno/Term/Thread Aware|thread aware]] as needed, if it is to be used in
 
* any environment (being [[Uno/Term/Thread Free|thread free]]), it may behave differently, depending on the managing environment.
 
Obviously, invisible threads can be used and created anytime anyway. Invisible threads do not harm [[Uno/Term/Thread Transparent|thread transparency]] by definition.
 
 
====Unsafe / Affine Code====
 
If you are writing [[Uno/Term/Thread Unsafe|thread unsafe]] code, the to be run thread needs to run outside the current (thread unsafe) environment. The objects, which should be used by this thread, need to be mapped to the threads environment, which typically will be the thread safe environment.
 
 
Mapped objects need to be managed by the belonging enviroment only, as long as this environment has not been entered explicity, otherwise methods (e.g. <code>release</code> or <code>acquire</code>) of the objects may be called from the wrong environment.
 
 
====C++====
 
Do not enter the environment explicity, but only implicity when calling methods on mapped objects (assuming the objects have been implemented in the target environment).
 
<pre>
 
class MyThread : public Thread
 
{
 
  uno::Reference<XInterface> m_xInterface;
 
 
public:
 
  MyThread(uno::Reference<XInterface> const & xInterface);
 
};
 
 
MyThread::MyThread(uno::Reference<XInterface> const & xInterface)
 
{
 
  uno::Mapping unsafe2safe(uno::getCurrentEnvironment(),
 
                          rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(CPPU_STRINGIFY(CPPU_ENV))));
 
 
  m_xInterface.set(unsafe2safe.mapInterface(pT, getCppuType(m_xInterface)),
 
  SAL_NO_ACQUIRE);
 
}
 
</pre>
 
 
Use the <code>shield</code> helper:
 
<pre>
 
class MyThread : public Thread
 
{
 
  uno::Reference<XInterface> m_xInterface;
 
 
public:
 
  MyThread(uno::Reference<XInterface> const & xInterface)
 
    : m_xInterface(uno::shield(xInterface), SAL_NO_ACQUIRE)
 
  {
 
  }
 
};
 
</pre>
 
 
Just enter the environment add do all calls while being in it. Obviously, releasing the objects also needs to be done in the environment.
 
<pre>
 
class MyThread : public Thread
 
{
 
  uno::Environment          m_refEnv;
 
  uno::Reference<XInterface> m_xInterface;
 
 
  void i_doSomething();
 
 
public:
 
  MyThread(uno::Reference<XInterface> const & xInterface);
 
 
  void doSomething();
 
};
 
 
MyThread::MyThread(uno::Reference<XInterface> const & xInterface)
 
: m_xInterface(xInterface), m_refEnv(uno::getCurrentEnvironment());
 
{
 
}
 
 
void MyThread::doSomething()
 
{
 
  // do not do any slow/blocking operations here, as the target environment is
 
  // currently entered, and no other thread may enter at the moment...
 
  m_xInterface->...
 
}
 
 
static void s_doSomething(va_list param)
 
{
 
  MyThread * pMyThread = va_arg(param, MyThread *);
 
  pMyThread->i_doSomething();
 
}
 
 
void MyThread::doSomething()
 
{
 
  m_refEnv.invoke(s_doSomething, this);
 
}
 
 
MyThread::~MyThread()
 
{
 
  m_refEnv.invoke(clearRefs);
 
}
 
</pre>
 
 
These may be eased by using the FreeReference.
 
  
 
===Implementation Types===
 
===Implementation Types===
Line 236: Line 142:
  
 
'''Note:''' The planned introduction of [[Uno/Spec/Implementation Environment|implementation environments]] is going to be usable by the application programmer as well. It basically removes the necessity to explicitly enter a particular [[Uno/Spec/Purpose Environment|purpose environment]].
 
'''Note:''' The planned introduction of [[Uno/Spec/Implementation Environment|implementation environments]] is going to be usable by the application programmer as well. It basically removes the necessity to explicitly enter a particular [[Uno/Spec/Purpose Environment|purpose environment]].
 +
 +
===Using Threads===
 +
You may create threads in your implementation. Depending on the selected threading architecture, these threads may are allowed to be visible from the outside or not. If your implementation is to be instantiated in a
 +
* [[Uno/Spec/Thread Unsafety Bridge|thread unsafe environment]], than it must be [[Uno/Term/Thread Transparent|thread transparent]], if it is to be used in a
 +
* [[Uno/Spec/Thread Affinity Bridge|thread affine environment]], than is must be [[Uno/Term/Thread Transparent|thread transparent]] as well, if it is to be used in a
 +
* [[Uno/Term/Thread Safe|thread safe]] environment, it may create visible threads and be [[Uno/Term/Thread Aware|thread aware]] as needed, if it is to be used in
 +
* any environment (being [[Uno/Term/Thread Free|thread free]]), it may behave differently, depending on the managing environment.
 +
Obviously, invisible threads can be used and created anytime anyway. Invisible threads do not harm [[Uno/Term/Thread Transparent|thread transparency]] by definition.
 +
 +
====Unsafe / Affine Code====
 +
If you are writing [[Uno/Term/Thread Unsafe|thread unsafe]] code, the to be run thread needs to run outside the current (thread unsafe) environment. The objects, which should be used by this thread, need to be mapped to the threads environment, which typically will be the thread safe environment.
 +
 +
Mapped objects need to be managed by the belonging enviroment only, as long as this environment has not been entered explicity, otherwise methods (e.g. <code>release</code> or <code>acquire</code>) of the objects may be called from the wrong environment.
 +
 +
====C++====
 +
Do not enter the environment explicity, but only implicity when calling methods on mapped objects (assuming the objects have been implemented in the target environment).
 +
<pre>
 +
class MyThread : public Thread
 +
{
 +
  uno::Reference<XInterface> m_xInterface;
 +
 +
public:
 +
  MyThread(uno::Reference<XInterface> const & xInterface);
 +
};
 +
 +
MyThread::MyThread(uno::Reference<XInterface> const & xInterface)
 +
{
 +
  uno::Mapping unsafe2safe(uno::getCurrentEnvironment(),
 +
                          rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(CPPU_STRINGIFY(CPPU_ENV))));
 +
 +
  m_xInterface.set(unsafe2safe.mapInterface(pT, getCppuType(m_xInterface)),
 +
  SAL_NO_ACQUIRE);
 +
}
 +
</pre>
 +
 +
Use the <code>shield</code> helper:
 +
<pre>
 +
class MyThread : public Thread
 +
{
 +
  uno::Reference<XInterface> m_xInterface;
 +
 +
public:
 +
  MyThread(uno::Reference<XInterface> const & xInterface)
 +
    : m_xInterface(uno::shield(xInterface), SAL_NO_ACQUIRE)
 +
  {
 +
  }
 +
};
 +
</pre>
 +
 +
Just enter the environment add do all calls while being in it. Obviously, releasing the objects also needs to be done in the environment.
 +
<pre>
 +
class MyThread : public Thread
 +
{
 +
  uno::Environment          m_refEnv;
 +
  uno::Reference<XInterface> m_xInterface;
 +
 +
  void i_doSomething();
 +
 +
public:
 +
  MyThread(uno::Reference<XInterface> const & xInterface);
 +
 +
  void doSomething();
 +
};
 +
 +
MyThread::MyThread(uno::Reference<XInterface> const & xInterface)
 +
: m_xInterface(xInterface), m_refEnv(uno::getCurrentEnvironment());
 +
{
 +
}
 +
 +
void MyThread::doSomething()
 +
{
 +
  // do not do any slow/blocking operations here, as the target environment is
 +
  // currently entered, and no other thread may enter at the moment...
 +
  m_xInterface->...
 +
}
 +
 +
static void s_doSomething(va_list param)
 +
{
 +
  MyThread * pMyThread = va_arg(param, MyThread *);
 +
  pMyThread->i_doSomething();
 +
}
 +
 +
void MyThread::doSomething()
 +
{
 +
  m_refEnv.invoke(s_doSomething, this);
 +
}
 +
 +
MyThread::~MyThread()
 +
{
 +
  m_refEnv.invoke(clearRefs);
 +
}
 +
</pre>
 +
 +
These may be eased by using the FreeReference.
  
 
===Relevant Specifications===
 
===Relevant Specifications===

Revision as of 08:01, 11 July 2006

Preface

The technologie described in this article depends on the presence of the Uno/Effort/Creating the Uno Threading Framework.

Multi Threading Programming

UNO is inherently multi threaded. Every instance of a UNO component (which is an object) may be accessed by multiple threads concurrently. The UNO threading framework provides support for simplifying multi thread programming.

Every UNO reference points to an object with particular characteristics. Among implementing a concrete interface, the object may belong to one or multiple Purpose Environments. The UNO threading model provides thread affine purpose environments and thread unsafe purpose environments. Objects not belonging to one of these two purpose environments are assumed to be thread safe.

Implementing Objects

Going to implement an UNO object, you need to decide on the threading architecture. You basically have the following choices, the object can either be

Thread Unsafe

Thread unsafe is the choice for most cases. Actually leaving proper synchronization of method calls to the runtime.

Thread Safe

There are only rare cases where you actually want to implement your object thread safe. Either

  • your object should or must allow the concurrent execution of some of its methods, or
  • your object wants to avoid the overhead associated with leaving synchronization to the runtime.

One case, where your component must allow the concurrent execution of methods is, when you want to be able to abort a running invocation. UNO currently does not offer a mechanism to do this generically, so that particular objects must provide dedicated methods for abortion. An example for this is the util/io/Acceptor implementation.

The overhead for automatic synchronization only affects inter-environment calls. The threading architecture of a particular application should be designed in a way, that closely connected objects happen to exist in the same environment. Basically ensuring a low inter-environment call frequency, converting the potential advantage of self synchronized methods to the reverse.

Note: Scalability may be achieved by the introduction of Named Environments, actually allowing any number of Thread Unsafe Purpose Environments to exist simultanesously and to be entered by multiple threads concurrently.

Thread Affine

Thread affine objects are rare. In OOo they are needed to encapsulate the Win32 respectively the OLE/COM thread affinity.

Thread Free

Thread free objects may be used in any threading environment. They certainly need to respect particular environment related constraints, so. An implementation being able to deal with one of thread unsafe, thread safe or thread affine objects only, is thread specialized on this particular threading model, while a thread free implementation is able to deal with any threading model.

Note: Unfortunately, no type safe purpose references are yet available for any UNO language binding. So, this is planned. Currently, the only possible way to detect the purpose of a reference is at runtime, via the getCurrentEnvironment runtime function.

Note: The UNO runtime provides APIs for implementing any whished scenario. Including objects shared between different purpose environments or the instantiation of a thread safe component in a thread unsafe environment. These mechanisms are in place to implement the threading framework itself, and to allow the programmer to gain full control, if needed.

Capabilities

Code may actually vary in its capabilities regarding 'transparent concurrency'. Code may be differentiated into code using

  • global variables, or
  • thread local variables, or
  • parameters only, or
  • value parameters only, or
  • doing internal protection of critical sections, or
  • not doing internal protection.

Such categorizations help to decide, what one can do with a particular implemention. Also the codes threading type is a compile time information and may therefor be used during compilation, so that the compiler may give errors when mixing thread safe and thread unsafe code in a multi thread scenario.

Implementation Types

Depending on the type of the planned implementation, which either is a

  • component, or a
  • library, or an
  • application,

care of the "purpose" characteristic of the involved objects needs to be taken.

Note: It is planned, to support the selection of an implementation environment (determining the implementations purpose environment) at compile time, e.g. for 'C' like languages by a macro or an include. Some experiments have been done, so no final decisions have been made yet.

Components

Components do provide their implementation environment. If a component should be implemented thread unsafe, this needs to be reflect in the target environment.

C++

Thread Specialized components directly return their ABI plus their thread related specialisation. The implementation of the component_getImplementationEnvironment function for a thread unsafe component needs to reflect this unsafeness by providing it together with the ABI, e.g.:

extern "C" void SAL_CALL component_getImplementationEnvironment(sal_Char        const ** ppEnvTypeName, 
								uno_Environment       ** ppEnv)
{
	*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ":unsafe";
}

A thread free component providing objects for all thread related environments needs to implement the component_getImplementationEnvironmentExt function, e.g.:

extern "C" void SAL_CALL component_getImplementationEnvironmentExt(sal_Char        const ** ppEnvTypeName, 
	                                                           uno_Environment       ** ppEnv,
	                                                           sal_Char        const  * pImplName,
                                                                   uno_Environment        * pSrcEnv
)
{
  rtl::OUString envName(RTL_CONSTASCII_USTRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING));
  envName += cppu::EnvDcp_getPurpose(Environment(pSrcEnv).getTypeName();

  uno_getEnvironment(ppEnv, envName.pData, NULL);
}

Implementing this function, the component may very well select the threading environments depending on the provided implementation names.

Libraries

Libraries can not rely on the runtime to handle thread (respectively purpose) related mapping. Libraries need to care of thread related environments by their own. As well as components or applications, libraries may be implemented thread specialized or thread free. Depending on the capabilities of the particular programming language and language binding, correct specialization may be ensured during compilation time, e.g. by dedicated reference types.

C++

The current C++ UNO language binding only supports free (cppu::FreeReference) and classic (com::sun::star::uno::Reference) references. The API of thread free libraries should reflect the "freeness" by using the cppu::FreeReference in its definition, e.g.:

// Declaration
cppu::FreeReference<XSingleServiceFactory> get_a_factory(void);

For compatibility reasons, classic UNO references (com::sun::star::uno::Reference) may be used, doing a runtime check for the thread type of the passed or requested objects, e.g.:

static void creator(va_list param) {
	cppu::FreeReference * prFactory = va_arg(param, cppu::FreeReference<XSingleServiceFactory> *);

    rFactory->set(new MyThreadUnsafeFactory());
}

// API Implementation
uno::Reference<XSingleServiceFactory> get_a_factory(void)
{
  cppu::FreeReference<XSingleServiceFactory> rFactory(new MyThreadUnsafeFactory());

  uno::Environment(rtl::OUString(RTL_CONSTASCII_PARAM("uno:unsafe"))).invoke(creator, &rFactory);

  return rFactory;
}

The cppuhelper library dynamically checks the current environment, and returns matching references, e.g. guaranteeing that thread safe and thread unsafe objects do not get mixed.

Applications

Applications are basically like libraries, except that no UNO objects are passed in, or are returned. Application code implemented other than in the thread safe environment needs to explicitly enter the wished purpose environment respectively thread related environment before calling any particular UNO aware thread specialized library. UNO aware libraries may than provide matching objects, depending on their threading architecture. By default, applications start in the thread safe environment.

C++

An application implementing thread unsafe objects to be passed to some UNO components may look like this:

class MyThreadUnsafeObject : ... {
  ...
};

SAL_IMPLEMENT_MAIN()
{
  cppu::EnvGuard unsafeGuard(Environment(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("uno:unsafe"))));

  // Get a thread unsafe component context.
  Reference< XComponentContext> xCtxt(cppu::defaultBootstrap_InitialComponentContext());
  ...
  xObject.set(new MyThreadUnsafeObject());
  ...
  return 0;
}

Note: The planned introduction of implementation environments is going to be usable by the application programmer as well. It basically removes the necessity to explicitly enter a particular purpose environment.

Using Threads

You may create threads in your implementation. Depending on the selected threading architecture, these threads may are allowed to be visible from the outside or not. If your implementation is to be instantiated in a

Obviously, invisible threads can be used and created anytime anyway. Invisible threads do not harm thread transparency by definition.

Unsafe / Affine Code

If you are writing thread unsafe code, the to be run thread needs to run outside the current (thread unsafe) environment. The objects, which should be used by this thread, need to be mapped to the threads environment, which typically will be the thread safe environment.

Mapped objects need to be managed by the belonging enviroment only, as long as this environment has not been entered explicity, otherwise methods (e.g. release or acquire) of the objects may be called from the wrong environment.

C++

Do not enter the environment explicity, but only implicity when calling methods on mapped objects (assuming the objects have been implemented in the target environment).

class MyThread : public Thread 
{
  uno::Reference<XInterface> m_xInterface;

public:
  MyThread(uno::Reference<XInterface> const & xInterface);
};

MyThread::MyThread(uno::Reference<XInterface> const & xInterface)
{
  uno::Mapping unsafe2safe(uno::getCurrentEnvironment(), 
                           rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(CPPU_STRINGIFY(CPPU_ENV))));
		
  m_xInterface.set(unsafe2safe.mapInterface(pT, getCppuType(m_xInterface)), 
		   SAL_NO_ACQUIRE);
}

Use the shield helper:

class MyThread : public Thread 
{
  uno::Reference<XInterface> m_xInterface;

public:
  MyThread(uno::Reference<XInterface> const & xInterface)
    : m_xInterface(uno::shield(xInterface), SAL_NO_ACQUIRE)
  {
  }
};

Just enter the environment add do all calls while being in it. Obviously, releasing the objects also needs to be done in the environment.

class MyThread : public Thread 
{
  uno::Environment           m_refEnv;
  uno::Reference<XInterface> m_xInterface;

  void i_doSomething();

public:
  MyThread(uno::Reference<XInterface> const & xInterface);

  void doSomething();
};

MyThread::MyThread(uno::Reference<XInterface> const & xInterface)
 : m_xInterface(xInterface), m_refEnv(uno::getCurrentEnvironment());
{
}

void MyThread::doSomething()
{
  // do not do any slow/blocking operations here, as the target environment is
  // currently entered, and no other thread may enter at the moment...
  m_xInterface->...
}

static void s_doSomething(va_list param)
{
  MyThread * pMyThread = va_arg(param, MyThread *);
  pMyThread->i_doSomething();
}

void MyThread::doSomething()
{
  m_refEnv.invoke(s_doSomething, this);
}

MyThread::~MyThread() 
{
  m_refEnv.invoke(clearRefs);
}

These may be eased by using the FreeReference.

Relevant Specifications

The relevant specifications can be found here:

In particular:

See also

Personal tools