I have a class, which has static function defined to work with C-style extern C { static void callback(foo bar) { } }
. // static is defined in header.
Three objects (each in separate pthread) are instant开发者_开发技巧iated from this class, each of them has own loop (in class constructor), which can receive the callback.
The pointer to function is passed as:
x = init_function(h, queue_id, &callback, NULL);
while(1) { loop_function(x); }
So each thread has the same pointer to &callback.
- Callback function can block for minutes.
- Each thread object, excluding the one which got the blocking callback, can call callback again.
- If the callback function exists only once, then any thread attempting to callback will also block. This would give me an undesired bug, circa is interesting to ask: can anything in C++ become acting this way? Maybe, due to extern { } or some pointer usage?
C++ doesn't know about threads. There is absolutely nothing which would cause one thread to block another automatically; you must use some OS or library functions to accomplish this. It is perfectly valid for any number of threads to call a single function simultaneously.
If you don't specifically code some sort of lock or call a function (including system functions) that has some sort of lock (like opening the same file for exclusive write access, etc.) then there is no way to "block" other threads. There is no automatic function locking in c or c++.
If the callback executes sleep(3600), that would not block other threads. Each thread would enter the callback and execute sleep(3600).
If you want threads to wait for critical code to execute, you must code the locking mechanism yourself. You generally activate the locking mechanism before executing the code (referred to commonly as "locking") and then you generally deactivate the lock after executing the code ("unlocking"). Linux coders generally use mutexes or gcc atomic operations to do this.
Sounds to me like you need to read some basic documentation about threads and multi threaded code and start from there. Here is one of a million articles on the basics of threading: link text
If the callback function exists only once, then any thread attempting to callback will also block. This would give me an undesired bug, circa is interesting to ask: can anything in C++ become acting this way? Maybe, due to extern { } or some pointer usage?
No and yes.
callback
is a simple function. It can be (in principle) called in parallel by two threads, and extern C
changes nothing about this.
However, if the implementation of the callback
function eg. waits on a mutex, it can surely block multiple threads.
精彩评论