I am programming with pthread in C language. I want a thread to tell other threads that it has put a message on the message queue, so that other threads would know that they can fetch messages from the message queue. However, the thread which has sent the signal should supply more information to other threads, such as thread id, message tag, and so on. How to do that ?
I know pthread_kill function, but It seems take little information. Can I take more information when I use a thread send signal to other threads ?
A signal in the C sense is not able to take "more information" - if you want to send more information, then you need to include that as part of the message in the message_queue, rather than as part of the signal.
I'm pretty sure there are dozens of alternatives. Just that you haven't thought of them. Like I said, if you want to use signals, then use a signal to indicate that there is a message (like the telephone ringing) then use a message queue to convey the actual information (talking on the phone). We don't use the phone ring signal to convey the message over the phone, right?
But I fear that you have somehow misunderstood the usage of threads and signals. I'm pretty sure that the way you are SUPPOSED to solve whatever you ar doing, isn't the right way.
Since your question is "How do I send more than an integer in a signal, I think you should accept Arno's answer, and then try again if that doesn't help - with a description of what your OVERALL problem is that you are trying to solve - right now you are talking to a mechanic about how to losen a bolt, but what you really need to do is fix a puncture, so you may be too concentrated on how to solve the detail, to muss the fact that you haven't even got a jack to lift the car off the ground...
Threads of a process share the same adress space. Thus it is common to build a mutex protected message queue for interthread communication. See this answer to get into the details. The message queue may be a custom design e.g. a linked list structure which may contain elements like sender ThreadID
, receiver ThreadID
, the message
, and optional any number of additional parameters
like message state or something. It may also contain a unique message ID
and a parameter to tell the receiving thread how to proceed, e.g. remove the message from the queue or not.
A signal can still be used to avoid polling the message queue for new messages. A signal will trigger threads to read the mutex protected message queue for new messages. Another way is to build up an event scheme, as described in this answer. But this is in fact also a mutex protected global identifier which is set and the waiting thread is polling for the change (so called busy wait). Could do the busy wait on the mutex protected message queue right away. See this link for more information about pthread_cond_wait
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With