我有一个日志记录应用程序。在特定时间(用户可配置时间)之后,我需要关闭当前日志文件并创建新的日志文件并记录数据。
我的程序中有两个关键代码段。
while(1)
)每当时间到期,我需要停止记录到文件并关闭它&打开新的日志文件并开始记录。
为此,我创建了一个与我的应用程序完全相同的示例应用程序,但是这里使用printf
而不是文件操作。
我正在使用pthread_cond_timedwait
调用来处理与计时器相关的操作。这是我的示例代码 -
#include <stdio.h>
#include <sys/time.h>
#include <errno.h>
#include <pthread.h>
/* For safe condition variable usage, must use a boolean predicate and */
/* a mutex with the condition. */
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
#define WAIT_TIME_SECONDS 10
void *threadfunc(void *parm)
{
int rc;
struct timespec abstime;
struct timeval now;
/* Usually worker threads will loop on these operations */
while (1) {
rc = gettimeofday(&now, NULL);
/* Convert from timeval to timespec */
abstime.tv_sec = now.tv_sec + WAIT_TIME_SECONDS;
abstime.tv_nsec = (now.tv_usec + 1000UL * WAIT_TIME_SECONDS) * 1000UL;
abstime.tv_sec += abstime.tv_nsec / (1000 * 1000 * 1000);
abstime.tv_nsec %= (1000 * 1000 * 1000);
printf("Thread blocked\n");
pthread_mutex_lock(&mutex);
rc = pthread_cond_timedwait(&cond, &mutex, &abstime);
pthread_mutex_unlock(&mutex);
printf("Wait timed out!\n");
/* critical section of code */
pthread_mutex_lock(&lock);
printf("Thread consumes work here\n");
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(int argc, char **argv)
{
int rc=0;
pthread_t threadid;
rc = pthread_create(&threadid, NULL, threadfunc, NULL);
if (rc != 0) {
printf("Thread creation failed err:%d\n", errno);
return -1;
}
while (1) {
/* critical section of code */
sleep(1);
pthread_mutex_lock(&lock);
printf("One work item to give to a thread\n");
pthread_mutex_unlock(&lock);
}
printf("Wait for threads and cleanup\n");
pthread_join(threadid, NULL);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
printf("Main completed\n");
return 0;
}
此代码无效。只要pthread_cond_timedwait
到期threadfunc
,函数就应该获取互斥lock
并且需要打印语句。打印完后释放互斥锁。但它没有发生。控件永远不会从main()
转移到threadfunc
。这里有什么问题?
但是如果我使用变量来处理代码的关键部分而不是互斥,那么就可以做到。说 -
static int stop = 0; // take a global variable
//inside threadfunc
/* critical section of code */
stop = 1; //Replace pthread_mutex_lock with this
printf("Thread consumes work here\n");
stop = 0; //Replace pthread_mutex_unlock with this
//in main()
while (1) {
/* critical section of code */
sleep(1);
if (!stop)
printf("One work item to give to a thread\n");
}
这种方法运作正常。
当我在代码中使用多个互斥锁时,我无法实现此功能。背后发生的真实事情是什么?在使用互斥锁处理代码的关键部分时,我是否遗漏了任何内容?
提前致谢!