Linux下執行緒的掛起和恢復
阿新 • • 發佈:2019-01-25
POSIX的Linux作業系統沒有提供執行緒掛起和恢復的例程,在網上找了找,看到一個老外寫的程式,感覺想法不錯,放在這裡大家分享一下。理論上應該可以實現,不過我沒有試,給大家提供一個參考。 (在讀取快取裡的資料時,當快取中沒有資料最好把執行緒掛起)
void CPrcThread ::suspend()
{
ifdef WIN32
//do windows specific things here...
#endif
#ifdef __linux__
pthread_mutex_lock(&mutex);
flag--;
pthread_mutex_unlock(&mutex);
#endif
}
void CPrcThread ::resume()
{
#ifdef WIN32
//do windows specific things here...
#endif
#ifdef __linux__
pthread_mutex_lock(&mutex);
flag++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
#endif
}
void* CPrcThread ::threadFunc(void* pParameter)
{
while(1)
{
#ifdef WIN32
//do windows specific things here...
//no member variables accessed here so its ok...
#endif
#ifdef __linux__
pthread_mutex_lock(&mutex);
while(flag <= 0)
{
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
#endif
//actual thread work here
}
}
void CPrcThread ::suspend()
{
ifdef WIN32
//do windows specific things here...
#endif
#ifdef __linux__
pthread_mutex_lock(&mutex);
flag--;
pthread_mutex_unlock(&mutex);
#endif
}
void CPrcThread ::resume()
{
#ifdef WIN32
//do windows specific things here...
#endif
#ifdef __linux__
pthread_mutex_lock(&mutex);
flag++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
#endif
}
void* CPrcThread ::threadFunc(void* pParameter)
{
while(1)
{
#ifdef WIN32
//do windows specific things here...
//no member variables accessed here so its ok...
#endif
#ifdef __linux__
pthread_mutex_lock(&mutex);
while(flag <= 0)
{
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
#endif
//actual thread work here
}
}