What is the best way to communicate between threads?

The best way to communicate between threads is sometimes also the best way to communicate between processes. However, when communicating between threads you can utilize two (very important) techniques:

Semaphores

In order to share application resources, and not write to the same space at the same time, you have to have some kind of flags that tell the thread when it should stop, when it should keep on going, and so on. Semaphores provide this capability. Semaphores are not for passing data. They merely exist as simple flags between threads and you should treat them as such.

Global Variables

"Hey Jeff - I thought this was supposed to be about nifty OS/2-specific tricks!" It is! You can now use those old nasty things, global variables, in new ways. In conjunction with semaphores, you can pass data very easily between threads with global variables. Here's a simple example:

  • Create a global variable called PassData.
  • Create a semaphore called OkToPassData.
  • Create a semaphore called DataPassed.
  • Have two threads work at the same time: