views:

343

answers:

1

I'm writing a network library that a user can pass a function pointer to for execution on certain network events. In order to keep the listening loop from holding up the developer's application, I pass the event handler to a thread. Unfortunately, this creates a bit of a headache for handling things in a thread-safe manner. For instance, if the developer passes a function that makes calls to their Windows::Forms application's elements, then an InvalidOperationException will be thrown.

Are there any good strategies for handling thread safety?

+2  A: 

Function pointers can not be thread safe as they declare a point to call. So they are just pointers. Your code always runs in the thread it was called from (via the function pointer).

What you want to achieve is that your code runs in a specific thread (maybe the UI thread). For this you must use some kind of queue to synchronize the invocation into the MainThread.

This is exactly what .Net's BeginInvoke()/Invoke() on a Form do. The queue is in that case (somewhere deep inside the .NET framework) the windows message queue.

But you can use any other queue as long as the "correct" thread reads and executes the call requests from that queue.

rstevens
I'm not sure if we disagree or not. "Your code always runs in the thread the function pointer was used to call it." I don't know what this means. if you meant to say: "Your code always runs in the thread the function pointer used to call it." then it is correct. Otherwise it sounds like you mean to say that the function that the pointer references will not a have a unique context when it is called, and that is incorrect.
San Jacinto
I edited the answer so now it is hopefully clear.
rstevens