Thursday, April 1, 2010

A tip on multithreading in PowerBuilder

The way you do multithreading in PowerBuilder is to create an object that contains the code you want to run in another thread. You then create an instance of this object as a “shared object”. You also code another object – the “interface object” and pass the shared object a reference to it. You can then call functions on the shared object and have them run in the other thread. The shared object communicates back to the main thread via the interface object.

The other day I set up a program using a shared object. I had a shared object that was running some code asynchronously. When it was done, it called a function on the interface object and the interface object called a function in my window to let me know it was complete (by setting a variable). At one point I needed to wait until the shared object was done with its processing before I continued what I was doing in the main thread. I had it coded something like this:


Integer li_status

Li_status = wf_get_status()

Do while li_status = NOT_COMPLETE
Li_status = wf_get_status()
Loop

I couldn’t figure out why it never exited the loop. Then I added a yield:

Integer li_status

Li_status = wf_get_status()

Do while li_status = NOT_COMPLETE
Yield()
Li_status = wf_get_status()
Loop

That worked. But it wasn’t until later that it hit me why. The other thread was completing and calling back into my thread – but since I was stuck in a loop and not yielding – I wasn’t letting the code in my thread that set the status variable run.

3 comments:

Toni said...
This comment has been removed by the author.
Toni said...
This comment has been removed by the author.
Toni said...

Hi, I have a question about your post.
When calling the shared object and passing the interface object as an argument, you can pass the interface object by value, but not by reference, because PowerBuilder won't allow you. So how do you work around that? Thanks in advance