How to block thread with timeout ?

I read /dev/ser1 in thread#1 (using notify())
and I want to wait in thread#2 until I read 4 chars or timeout occur (5 s).

How to do that?
/not by polling (it gets processor time/power)

Oink,

In thread 2 you create a channel and then wait on that channel to see if you get your timer or thread 1 receives 4 characters.

Roughly via psuedo code you do the following:

int channelId = ChannelCreate(0) // Creates a channel

int connectId = ConnectAttach(0, 0, channelId, _NTO_SIDE_CHANNEL, 0); // Connect to the channel

// You now have a channel to send/receive messages on between your 2 threads. You need to make the 2 variables above viewable from thread 1 so that thread can send messages to thread 2.

// Create a timer
struct sigevent event;

event.sigev_notify = SIGEV_PULSE;
event.sigev_coid = ConnectAttach(0, 0, channelId, _NTO_SIDE_CHANNEL, 0);
event.sigev_priority = getprio(0);
event.sigev_code = 99; // Timer will deliver a 99 when it expires

int timerId = TimerCreate(CLOCK_REALTIME, &event)) < 0)

// You now have a timer that also uses the same channel as the messages between threads.

// I will leave it to you to set up the timing parameters for 5 seconds and to start the actual timer.

// Now wait for a message or a timer (this is thread 2 code)

union Message
{
// 4 bytes of data from thread 1
char msg[4];
// This structure contains timer events from QNX
struct _pulse timerPulse;
};

Message msg;

int recvId = MsgReceive(channelId, &msg, sizeof(Message), NULL);

// Determine if we received a message from thread 1 or a timer pulse (lots more code goes in here but this is the basics of how you tell).

if (recvId == 0)
{
// We go a timer timeout
}
else
{
// We got a message from thread 1
}

// In thread 1, when you have received 4 bytes of data you do

Message msg;
memcpy (msg.msg, data, 4); // Add your data

MsgSend(connectId, &msg, sizeof(Message), NULL, NULL);

Tim

…and this way doesn’t take processor time while is waiting for pulse receive ?

Oink.

Nope. Your blocked in thread 2 waiting for either the timer to expire or thread 1 to send a message. The kernal automatically wakes up thread 2 when either of the above conditions are true.

Tim

I know that, but is that way better than polling (checkin var. value in loop) ? :slight_smile:

that’s much much much better. But why do you need 2 threads for that, the first thread can deal with the timeout and the serial port.

You may have a problem though if your timeout value is smaller then 1ms.

Look at readcond(). It does what you want.

-seanb