|
Blue Forest http://www.lslnet.com at 10:18 on June 6, 2006
Pthread_cond_timedwait a strange question to ask experts 8 sparc solaris systems :
Gcc 3.2.2
In multithreaded programming, using the pthread_cond_timedwait A thread at a wait state, thread B with pthread_cond_signal sent simultaneously, but often simultaneously invalid, it's clear that the wait A, B signal installed, A still timeout, may ask what is the problem?
//bow
Output :
Start wait
Start send
Sent signal
End wait
Timeout!
Start wait
Start send
Sent signal
End wait
Timeout!
......
FOSS attached :
#include "Stdlib.h>;
#include "Stdio.h>;
#include "Pthread.h>;
#include "Unistd.h>;
#include "Sys/errno.h>;
Bool gbRun, gbRun1, gbRun2;
Pthread_mutex_t m_mutSend=PTHREAD_MUTEX_INITIALIZER;
Pthread_cond_t m_condSend=PTHREAD_COND_INITIALIZER;
Pthread_mutex_t m_mutWait=PTHREAD_MUTEX_INITIALIZER;
Pthread_cond_t m_condWait=PTHREAD_COND_INITIALIZER;
Pthread_t glbSend, glbRecv;
# 500 INTERVAL_SEND
Int msleep (int mseconds)
{
Struct timeval dval;
Dval.tv_sec = mseconds/1000;
Dval.tv_usec = (mseconds%1000) *1000;
Return select (0, NULL, NULL, NULL, &dval);
}
Void* threadSend (void* a)
{
Int Rifa
Struct timeval now;
Struct timespec timeout;
While (gbRun)
{
Pthread_mutex_lock (&m_mutWait);
Gettimeofday (&now, NULL);
Int ns= (now.tv_usec+ (INTERVAL_SEND%1000) ≤) *1000;
Timeout.tv_sec=now.tv_sec+INTERVAL_SEND/1000+ns/1000000000;
Timeout.tv_nsec=ns%1000000000;
Int ret=pthread_cond_timedwait (&m_condWait, &m_mutWait, &timeout);
If (ret==ETIMEDOUT)
{
Printf ( "start send\n");
Pthread_mutex_lock (&m_mutSend);
Pthread_cond_broadcast (&m_condSend);
Pthread_mutex_unlock (&m_mutSend);
Printf ( "sent signal\n");
}
Pthread_mutex_unlock (&m_mutWait);
}
}
Void* threadRecv (void* a)
{
Struct timeval now;
Struct timespec timeout;
Pthread_mutex_lock (&m_mutSend);
While (gbRun)
{
Gettimeofday (&now, NULL);
Int ns= (now.tv_usec+ (INTERVAL_SEND%1000) ≤) *1000;
Timeout.tv_sec=now.tv_sec+INTERVAL_SEND/1000+ns/1000000000;
Timeout.tv_nsec=ns%1000000000;
Printf ( "start wait\n");
Int ret=pthread_cond_timedwait (&m_condSend, &m_mutSend, &timeout);
Printf ( "end wait\n");
If (ret==ETIMEDOUT)
{
Printf ( "Timeout!\n");
}
Else
{
Printf ( "Received!\n");
}
}
Pthread_mutex_unlock (&m_mutSend);
}
Int main (void)
{
Int i, ret;
Int a=2;
GbRun = 1;
Ret=pthread_create (&glbSend, NULL, threadSend (void*) a);
If (ret!=0)
{
Printf ( "Create pthread error!%d\n", ret);
Exit (1);
}
Ret=pthread_create (&glbRecv, NULL, threadRecv (void*) a);
If (ret!=0)
{
Printf ( "Create pthread error!%d\n", ret);
Exit (1);
}
Printf ( "Start Test.\n");
Msleep (2000);
GbRun = 0
Pthread_join (glbSend, NULL);
Pthread_join (glbRecv, NULL);
Printf ( "End Test.\n");
Return (0);
} |
| |