需求:设置超时时间,当信号量等待时间过长时返回错误码,而非一直阻塞。效果类似于windows的WaitForSingleObject。
不废话了直接上代码:
// main.cpp
#include <semaphore.h>
#include <unistd.h>
#include <iostream>
#include <thread>
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
using namespace std;sem_t g_stSem;int Post_t(void *pvArg)
{sleep(1);sem_post(&g_stSem);sleep(5);sem_post(&g_stSem);return 0;
}int main()
{sem_init(&g_stSem, 0, 0);thread *pobjThrd = new thread(Post_t, nullptr);struct timespec ts;clock_gettime(CLOCK_REALTIME, &ts);ts.tv_sec += 2;int r = sem_timedwait(&g_stSem, &ts);if(r == 0) cout << "ok 1" << endl;else if(r == -1 && errno == ETIMEDOUT) cout << "timeout" << endl;else cout << "unknown error" << endl;clock_gettime(CLOCK_REALTIME, &ts);ts.tv_sec += 2;r = sem_timedwait(&g_stSem, &ts);if(r == 0) cout << "ok 2" << endl;else if(r == -1 && errno == ETIMEDOUT) cout << "timeout" << endl;else cout << "unknown error" << endl;if(pobjThrd){pobjThrd->join();delete pobjThrd;}sem_destroy(&g_stSem);return 0;
}
注意事项:sem_timedwait输入的是中止等待的时间戳,必须先用clock_gettime(CLOCK_REALTIME, &ts) 获取当前时间戳再加上等待时间才能得到正确的值。例程的2次等待都是2秒。
---完---