SDK Multithreading

From ActiveWiki
Jump to navigation Jump to search

Multithreading Model used by the SDK

SDK build 100 to 127 introduced a first level of multithreading by using TLS - Thread Local Storage. SDK 100 was available in 2 branches, non-thread safe and TLS. This had forced an application to access attributes and methods of a SDK instance on a certain thread only.

Prior to SDK build 100 multithreading was not supported by the SDK and the application had to take care of proper thread locking.

SDK build 131 and later dropped TLS and introduced scoped thread locking per method - making multithreading more flexible when designing applications.


Single threaded applications do not need to consider anything mentioned below. Applications designed with a multithreaded concept, only need to wrap thread locking around attribute access. A pair of additional methods have been introduced accessing the internal recursive thread lock.


External aquire of the internal lock:

   aw_thread_lock_aquire();

External release of the internal lock, MUST follow aquire on the same thread:

   aw_thread_lock_release();


Examples:

The main thread, typically the UI thread:

   ...
   aw_wait(0); // trigger events and callbacks in the main thread
   ...


In another worker thread, if you need to set attributes:

 int some_thread_fn()
 {
   int rc;
   aw_thread_lock_aquire();
   aw_int_set(AW_MY_X, 1000);   // 1W
   aw_int_set(AW_MY_Z, 1000);   // 1N
   aw_int_set(AW_MY_YAW, 2250); // face towards GZ
   if (rc = aw_state_change()) {
      printf ("Unable to change state (reason %d)\n", rc);
      aw_thread_lock_release(); // lock MUST be released by application
      return rc;
   }
   aw_thread_lock_release();    // lock MUST be released by application
   return 0;
 }

In another worker thread, if no attributes are needed methods use scoped thread locks internally:

 int another_thread_fn(const char* utf8_string)
 {
   int rc;
   // no explicit thread lock needed
   if (rc = aw_say(utf8_string)) {
      printf ("Unable to chat (reason %d)\n", rc);
      return rc;
   }
   return 0;
 }